file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/* Copyright 2017 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.4.11; import "./Ownable.sol"; contract Authorizable is Ownable { /// @dev Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; emit LogAuthorizedAddressAdded(target, msg.sender); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; emit LogAuthorizedAddressRemoved(target, msg.sender); } }
Authorizes an address. target Address to authorize.
function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; emit LogAuthorizedAddressAdded(target, msg.sender); }
12,844,754
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_ECDSAContractAccount } from "../../iOVM/accounts/iOVM_ECDSAContractAccount.sol"; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_ECDSAUtils } from "../../libraries/utils/Lib_ECDSAUtils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; import { Lib_SafeMathWrapper } from "../../libraries/wrappers/Lib_SafeMathWrapper.sol"; /** * @title OVM_ECDSAContractAccount * @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the * ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by * providing eth_sign and EIP155 formatted transaction encodings. * * Compiler used: solc * Runtime target: OVM */ contract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount { /************* * Constants * *************/ // TODO: should be the amount sufficient to cover the gas costs of all of the transactions up // to and including the CALL/CREATE which forms the entrypoint of the transaction. uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000; address constant ETH_ERC20_ADDRESS = 0x4200000000000000000000000000000000000006; /******************** * Public Functions * ********************/ /** * Executes a signed transaction. * @param _transaction Signed EOA transaction. * @param _signatureType Hashing scheme used for the transaction (e.g., ETH signed message). * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. * @return Whether or not the call returned (rather than reverted). * @return Data returned by the call. */ function execute( bytes memory _transaction, Lib_OVMCodec.EOASignatureType _signatureType, uint8 _v, bytes32 _r, bytes32 _s ) override public returns ( bool, bytes memory ) { bool isEthSign = _signatureType == Lib_OVMCodec.EOASignatureType.ETH_SIGNED_MESSAGE; // Address of this contract within the ovm (ovmADDRESS) should be the same as the // recovered address of the user who signed this message. This is how we manage to shim // account abstraction even though the user isn't a contract. // Need to make sure that the transaction nonce is right and bump it if so. Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_ECDSAUtils.recover( _transaction, isEthSign, _v, _r, _s ) == Lib_SafeExecutionManagerWrapper.safeADDRESS(), "Signature provided for EOA transaction execution is invalid." ); Lib_OVMCodec.EIP155Transaction memory decodedTx = Lib_OVMCodec.decodeEIP155Transaction(_transaction, isEthSign); // Need to make sure that the transaction chainId is correct. Lib_SafeExecutionManagerWrapper.safeREQUIRE( decodedTx.chainId == Lib_SafeExecutionManagerWrapper.safeCHAINID(), "Transaction chainId does not match expected OVM chainId." ); // Need to make sure that the transaction nonce is right. Lib_SafeExecutionManagerWrapper.safeREQUIRE( decodedTx.nonce == Lib_SafeExecutionManagerWrapper.safeGETNONCE(), "Transaction nonce does not match the expected nonce." ); // TEMPORARY: Disable gas checks for mainnet. // // Need to make sure that the gas is sufficient to execute the transaction. // Lib_SafeExecutionManagerWrapper.safeREQUIRE( // gasleft() >= Lib_SafeMathWrapper.add(decodedTx.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD), // "Gas is not sufficient to execute the transaction." // ); // Transfer fee to relayer. address relayer = Lib_SafeExecutionManagerWrapper.safeCALLER(); uint256 fee = Lib_SafeMathWrapper.mul(decodedTx.gasLimit, decodedTx.gasPrice); (bool success, ) = Lib_SafeExecutionManagerWrapper.safeCALL( gasleft(), ETH_ERC20_ADDRESS, abi.encodeWithSignature("transfer(address,uint256)", relayer, fee) ); Lib_SafeExecutionManagerWrapper.safeREQUIRE( success == true, "Fee was not transferred to relayer." ); // Contract creations are signalled by sending a transaction to the zero address. if (decodedTx.to == address(0)) { (address created, bytes memory revertData) = Lib_SafeExecutionManagerWrapper.safeCREATE( gasleft(), decodedTx.data ); // Return true if the contract creation succeeded, false w/ revertData otherwise. if (created != address(0)) { return (true, abi.encode(created)); } else { return (false, revertData); } } else { // We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps // the nonce of the calling account. Normally an EOA would bump the nonce for both // cases, but since this is a contract we'd end up bumping the nonce twice. Lib_SafeExecutionManagerWrapper.safeINCREMENTNONCE(); return Lib_SafeExecutionManagerWrapper.safeCALL( gasleft(), decodedTx.to, decodedTx.data ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_ECDSAUtils } from "../../libraries/utils/Lib_ECDSAUtils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title OVM_ProxyEOA * @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation contract. * In combination with the logic implemented in the ECDSA Contract Account, this enables a form of upgradable * 'account abstraction' on layer 2. * * Compiler used: solc * Runtime target: OVM */ contract OVM_ProxyEOA { /************* * Constants * *************/ bytes32 constant IMPLEMENTATION_KEY = 0xdeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead; /*************** * Constructor * ***************/ /** * @param _implementation Address of the initial implementation contract. */ constructor( address _implementation ) { _setImplementation(_implementation); } /********************* * Fallback Function * *********************/ fallback() external { (bool success, bytes memory returndata) = Lib_SafeExecutionManagerWrapper.safeDELEGATECALL( gasleft(), getImplementation(), msg.data ); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { Lib_SafeExecutionManagerWrapper.safeREVERT( string(returndata) ); } } /******************** * Public Functions * ********************/ /** * Changes the implementation address. * @param _implementation New implementation address. */ function upgrade( address _implementation ) external { Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_SafeExecutionManagerWrapper.safeADDRESS() == Lib_SafeExecutionManagerWrapper.safeCALLER(), "EOAs can only upgrade their own EOA implementation" ); _setImplementation(_implementation); } /** * Gets the address of the current implementation. * @return Current implementation address. */ function getImplementation() public returns ( address ) { return Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( IMPLEMENTATION_KEY ) ); } /********************** * Internal Functions * **********************/ function _setImplementation( address _implementation ) internal { Lib_SafeExecutionManagerWrapper.safeSSTORE( IMPLEMENTATION_KEY, Lib_Bytes32Utils.fromAddress(_implementation) ); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol"; /* Interface Imports */ import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /* Contract Imports */ import { OVM_ECDSAContractAccount } from "../accounts/OVM_ECDSAContractAccount.sol"; import { OVM_ProxyEOA } from "../accounts/OVM_ProxyEOA.sol"; import { OVM_DeployerWhitelist } from "../predeploys/OVM_DeployerWhitelist.sol"; /** * @title OVM_ExecutionManager * @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed * environment allowing us to execute OVM transactions deterministically on either Layer 1 or * Layer 2. * The EM's run() function is the first function called during the execution of any * transaction on L2. * For each context-dependent EVM operation the EM has a function which implements a corresponding * OVM operation, which will read state from the State Manager contract. * The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any * context-dependent operations. * * Compiler used: solc * Runtime target: EVM */ contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver { /******************************** * External Contract References * ********************************/ iOVM_SafetyChecker internal ovmSafetyChecker; iOVM_StateManager internal ovmStateManager; /******************************* * Execution Context Variables * *******************************/ GasMeterConfig internal gasMeterConfig; GlobalContext internal globalContext; TransactionContext internal transactionContext; MessageContext internal messageContext; TransactionRecord internal transactionRecord; MessageRecord internal messageRecord; /************************** * Gas Metering Constants * **************************/ address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5; uint256 constant NUISANCE_GAS_SLOAD = 20000; uint256 constant NUISANCE_GAS_SSTORE = 20000; uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000; uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100; uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000; /************************** * Default Context Values * **************************/ uint256 constant DEFAULT_UINT256 = 0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d; address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, GasMeterConfig memory _gasMeterConfig, GlobalContext memory _globalContext ) Lib_AddressResolver(_libAddressManager) { ovmSafetyChecker = iOVM_SafetyChecker(resolve("OVM_SafetyChecker")); gasMeterConfig = _gasMeterConfig; globalContext = _globalContext; _resetContext(); } /********************** * Function Modifiers * **********************/ /** * Applies dynamically-sized refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of the ovmOPCODE is fixed. * @param _cost Desired gas cost for the function after the refund. */ modifier netGasCost( uint256 _cost ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund everything *except* the specified cost. if (_cost < gasUsed) { transactionRecord.ovmGasRefund += gasUsed - _cost; } } /** * Applies a fixed-size gas refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered. * @param _discount Amount of gas cost to refund for the ovmOPCODE. */ modifier fixedGasDiscount( uint256 _discount ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund the specified _discount, unless this risks underflow. if (_discount < gasUsed) { transactionRecord.ovmGasRefund += _discount; } else { // refund all we can without risking underflow. transactionRecord.ovmGasRefund += gasUsed; } } /** * Makes sure we're not inside a static context. */ modifier notStatic() { if (messageContext.isStatic == true) { _revertWithFlag(RevertFlag.STATIC_VIOLATION); } _; } /************************************ * Transaction Execution Entrypoint * ************************************/ /** * Starts the execution of a transaction via the OVM_ExecutionManager. * @param _transaction Transaction data to be executed. * @param _ovmStateManager iOVM_StateManager implementation providing account state. */ function run( Lib_OVMCodec.Transaction memory _transaction, address _ovmStateManager ) override public { // Make sure that run() is not re-enterable. This condition should awlways be satisfied // Once run has been called once, due to the behvaior of _isValidInput(). if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // Store our OVM_StateManager instance (significantly easier than attempting to pass the // address around in calldata). ovmStateManager = iOVM_StateManager(_ovmStateManager); // Make sure this function can't be called by anyone except the owner of the // OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because // this would make the `run` itself invalid. require( // This method may return false during fraud proofs, but always returns true in L2 nodes' State Manager precompile. ovmStateManager.isAuthenticated(msg.sender), "Only authenticated addresses in ovmStateManager can call this function" ); // Initialize the execution context, must be initialized before we perform any gas metering // or we'll throw a nuisance gas error. _initContext(_transaction); // TEMPORARY: Gas metering is disabled for minnet. // // Check whether we need to start a new epoch, do so if necessary. // _checkNeedsNewEpoch(_transaction.timestamp); // Make sure the transaction's gas limit is valid. We don't revert here because we reserve // reverts for INVALID_STATE_ACCESS. if (_isValidInput(_transaction) == false) { _resetContext(); return; } // TEMPORARY: Gas metering is disabled for minnet. // // Check gas right before the call to get total gas consumed by OVM transaction. // uint256 gasProvided = gasleft(); // Run the transaction, make sure to meter the gas usage. ovmCALL( _transaction.gasLimit - gasMeterConfig.minTransactionGasLimit, _transaction.entrypoint, _transaction.data ); // TEMPORARY: Gas metering is disabled for minnet. // // Update the cumulative gas based on the amount of gas used. // uint256 gasUsed = gasProvided - gasleft(); // _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin); // Wipe the execution context. _resetContext(); } /****************************** * Opcodes: Execution Context * ******************************/ /** * @notice Overrides CALLER. * @return _CALLER Address of the CALLER within the current message context. */ function ovmCALLER() override public view returns ( address _CALLER ) { return messageContext.ovmCALLER; } /** * @notice Overrides ADDRESS. * @return _ADDRESS Active ADDRESS within the current message context. */ function ovmADDRESS() override public view returns ( address _ADDRESS ) { return messageContext.ovmADDRESS; } /** * @notice Overrides TIMESTAMP. * @return _TIMESTAMP Value of the TIMESTAMP within the transaction context. */ function ovmTIMESTAMP() override public view returns ( uint256 _TIMESTAMP ) { return transactionContext.ovmTIMESTAMP; } /** * @notice Overrides NUMBER. * @return _NUMBER Value of the NUMBER within the transaction context. */ function ovmNUMBER() override public view returns ( uint256 _NUMBER ) { return transactionContext.ovmNUMBER; } /** * @notice Overrides GASLIMIT. * @return _GASLIMIT Value of the block's GASLIMIT within the transaction context. */ function ovmGASLIMIT() override public view returns ( uint256 _GASLIMIT ) { return transactionContext.ovmGASLIMIT; } /** * @notice Overrides CHAINID. * @return _CHAINID Value of the chain's CHAINID within the global context. */ function ovmCHAINID() override public view returns ( uint256 _CHAINID ) { return globalContext.ovmCHAINID; } /********************************* * Opcodes: L2 Execution Context * *********************************/ /** * @notice Specifies from which L1 rollup queue this transaction originated from. * @return _queueOrigin Address of the ovmL1QUEUEORIGIN within the current message context. */ function ovmL1QUEUEORIGIN() override public view returns ( Lib_OVMCodec.QueueOrigin _queueOrigin ) { return transactionContext.ovmL1QUEUEORIGIN; } /** * @notice Specifies which L1 account, if any, sent this transaction by calling enqueue(). * @return _l1TxOrigin Address of the account which sent the tx into L2 from L1. */ function ovmL1TXORIGIN() override public view returns ( address _l1TxOrigin ) { return transactionContext.ovmL1TXORIGIN; } /******************** * Opcodes: Halting * ********************/ /** * @notice Overrides REVERT. * @param _data Bytes data to pass along with the REVERT. */ function ovmREVERT( bytes memory _data ) override public { _revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data); } /****************************** * Opcodes: Contract Creation * ******************************/ /** * @notice Overrides CREATE. * @param _bytecode Code to be used to CREATE a new contract. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE( bytes memory _bytecode ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE address. address contractAddress = Lib_EthUtils.getAddressForCREATE( creator, _getAccountNonce(creator) ); return _createContract( contractAddress, _bytecode ); } /** * @notice Overrides CREATE2. * @param _bytecode Code to be used to CREATE2 a new contract. * @param _salt Value used to determine the contract's address. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE2( bytes memory _bytecode, bytes32 _salt ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE2 address. address contractAddress = Lib_EthUtils.getAddressForCREATE2( creator, _bytecode, _salt ); return _createContract( contractAddress, _bytecode ); } /******************************* * Account Abstraction Opcodes * ******************************/ /** * Retrieves the nonce of the current ovmADDRESS. * @return _nonce Nonce of the current contract. */ function ovmGETNONCE() override public returns ( uint256 _nonce ) { return _getAccountNonce(ovmADDRESS()); } /** * Bumps the nonce of the current ovmADDRESS by one. */ function ovmINCREMENTNONCE() override public notStatic { address account = ovmADDRESS(); uint256 nonce = _getAccountNonce(account); // Prevent overflow. if (nonce + 1 > nonce) { _setAccountNonce(account, nonce + 1); } } /** * Creates a new EOA contract account, for account abstraction. * @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks * because the contract we're creating is trusted (no need to do safety checking or to * handle unexpected reverts). Doesn't need to return an address because the address is * assumed to be the user's actual address. * @param _messageHash Hash of a message signed by some user, for verification. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) override public notStatic { // Recover the EOA address from the message hash and signature parameters. Since we do the // hashing in advance, we don't have handle different message hashing schemes. Even if this // function were to return the wrong address (rather than explicitly returning the zero // address), the rest of the transaction would simply fail (since there's no EOA account to // actually execute the transaction). address eoa = ecrecover( _messageHash, _v + 27, _r, _s ); // Invalid signature is a case we proactively handle with a revert. We could alternatively // have this function return a `success` boolean, but this is just easier. if (eoa == address(0)) { ovmREVERT(bytes("Signature provided for EOA contract creation is invalid.")); } // If the user already has an EOA account, then there's no need to perform this operation. if (_hasEmptyAccount(eoa) == false) { return; } // We always need to initialize the contract with the default account values. _initPendingAccount(eoa); // Temporarily set the current address so it's easier to access on L2. address prevADDRESS = messageContext.ovmADDRESS; messageContext.ovmADDRESS = eoa; // Now actually create the account and get its bytecode. We're not worried about reverts // (other than out of gas, which we can't capture anyway) because this contract is trusted. OVM_ProxyEOA proxyEOA = new OVM_ProxyEOA(0x4200000000000000000000000000000000000003); // Reset the address now that we're done deploying. messageContext.ovmADDRESS = prevADDRESS; // Commit the account with its final values. _commitPendingAccount( eoa, address(proxyEOA), keccak256(Lib_EthUtils.getCode(address(proxyEOA))) ); _setAccountNonce(eoa, 0); } /********************************* * Opcodes: Contract Interaction * *********************************/ /** * @notice Overrides CALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(100000) returns ( bool _success, bytes memory _returndata ) { // CALL updates the CALLER and ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /** * @notice Overrides STATICCALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmSTATICCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(80000) returns ( bool _success, bytes memory _returndata ) { // STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static context. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /** * @notice Overrides DELEGATECALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmDELEGATECALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(40000) returns ( bool _success, bytes memory _returndata ) { // DELEGATECALL does not change anything about the message context. MessageContext memory nextMessageContext = messageContext; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /************************************ * Opcodes: Contract Storage Access * ************************************/ /** * @notice Overrides SLOAD. * @param _key 32 byte key of the storage slot to load. * @return _value 32 byte value of the requested storage slot. */ function ovmSLOAD( bytes32 _key ) override public netGasCost(40000) returns ( bytes32 _value ) { // We always SLOAD from the storage of ADDRESS. address contractAddress = ovmADDRESS(); return _getContractStorage( contractAddress, _key ); } /** * @notice Overrides SSTORE. * @param _key 32 byte key of the storage slot to set. * @param _value 32 byte value for the storage slot. */ function ovmSSTORE( bytes32 _key, bytes32 _value ) override public notStatic netGasCost(60000) { // We always SSTORE to the storage of ADDRESS. address contractAddress = ovmADDRESS(); _putContractStorage( contractAddress, _key, _value ); } /********************************* * Opcodes: Contract Code Access * *********************************/ /** * @notice Overrides EXTCODECOPY. * @param _contract Address of the contract to copy code from. * @param _offset Offset in bytes from the start of contract code to copy beyond. * @param _length Total number of bytes to copy from the contract's code. * @return _code Bytes of code copied from the requested contract. */ function ovmEXTCODECOPY( address _contract, uint256 _offset, uint256 _length ) override public returns ( bytes memory _code ) { // `ovmEXTCODECOPY` is the only overridden opcode capable of producing exactly one byte of // return data. By blocking reads of one byte, we're able to use the condition that an // OVM_ExecutionManager function return value having a length of exactly one byte indicates // an error without an explicit revert. If users were able to read a single byte, they // could forcibly trigger behavior that should only be available to this contract. uint256 length = _length == 1 ? 2 : _length; return Lib_EthUtils.getCode( _getAccountEthAddress(_contract), _offset, length ); } /** * @notice Overrides EXTCODESIZE. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function ovmEXTCODESIZE( address _contract ) override public returns ( uint256 _EXTCODESIZE ) { return Lib_EthUtils.getCodeSize( _getAccountEthAddress(_contract) ); } /** * @notice Overrides EXTCODEHASH. * @param _contract Address of the contract to query the hash of. * @return _EXTCODEHASH Hash of the requested contract. */ function ovmEXTCODEHASH( address _contract ) override public returns ( bytes32 _EXTCODEHASH ) { return Lib_EthUtils.getCodeHash( _getAccountEthAddress(_contract) ); } /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view override returns ( uint256 _maxTransactionGasLimit ) { return gasMeterConfig.maxTransactionGasLimit; } /******************************************** * Public Functions: Deployment Whitelisting * ********************************************/ /** * Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2, and reverts if not. * @param _deployerAddress Address attempting to deploy a contract. */ function _checkDeployerAllowed( address _deployerAddress ) internal { // From an OVM semantics perspective, this will appear identical to // the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to. (bool success, bytes memory data) = ovmCALL( gasleft(), 0x4200000000000000000000000000000000000002, abi.encodeWithSignature("isDeployerAllowed(address)", _deployerAddress) ); bool isAllowed = abi.decode(data, (bool)); if (!isAllowed || !success) { _revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED); } } /******************************************** * Internal Functions: Contract Interaction * ********************************************/ /** * Creates a new contract and associates it with some contract address. * @param _contractAddress Address to associate the created contract with. * @param _bytecode Bytecode to be used to create the contract. * @return Final OVM contract address. * @return Revertdata, if and only if the creation threw an exception. */ function _createContract( address _contractAddress, bytes memory _bytecode ) internal returns ( address, bytes memory ) { // We always update the nonce of the creating account, even if the creation fails. _setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1); // We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point // to the contract's associated address and CALLER to point to the previous ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = messageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _contractAddress; // Run the common logic which occurs between call-type and create-type messages, // passing in the creation bytecode and `true` to trigger create-specific logic. (bool success, bytes memory data) = _handleExternalMessage( nextMessageContext, gasleft(), _contractAddress, _bytecode, true ); // Yellow paper requires that address returned is zero if the contract deployment fails. return ( success ? _contractAddress : address(0), data ); } /** * Calls the deployed contract associated with a given address. * @param _nextMessageContext Message context to be used for the call. * @param _gasLimit Amount of gas to be passed into this call. * @param _contract OVM address to be called. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function _callContract( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { // We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2 geth. // So, we block calls to these addresses since they are not safe to run as an OVM contract itself. if ( (uint256(_contract) & uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000)) == uint256(0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000) ) { // EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604 return (true, hex''); } // Both 0x0000... and the EVM precompiles have the same address on L1 and L2 --> no trie lookup needed. address codeContractAddress = uint(_contract) < 100 ? _contract : _getAccountEthAddress(_contract); return _handleExternalMessage( _nextMessageContext, _gasLimit, codeContractAddress, _calldata, false ); } /** * Handles all interactions which involve the execution manager calling out to untrusted code (both calls and creates). * Ensures that OVM-related measures are enforced, including L2 gas refunds, nuisance gas, and flagged reversions. * * @param _nextMessageContext Message context to be used for the external message. * @param _gasLimit Amount of gas to be passed into this message. * @param _contract OVM address being called or deployed to * @param _data Data for the message (either calldata or creation code) * @param _isCreate Whether this is a create-type message. * @return Whether or not the message (either a call or deployment) succeeded. * @return Data returned by the message. */ function _handleExternalMessage( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _data, bool _isCreate ) internal returns ( bool, bytes memory ) { // We need to switch over to our next message context for the duration of this call. MessageContext memory prevMessageContext = messageContext; _switchMessageContext(prevMessageContext, _nextMessageContext); // Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs // expensive by touching a lot of different accounts or storage slots. Since most contracts // only use a few storage slots during any given transaction, this shouldn't be a limiting // factor. uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft; uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit); messageRecord.nuisanceGasLeft = nuisanceGasLimit; // Make the call and make sure to pass in the gas limit. Another instance of hidden // complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert // behavior can be controlled. In particular, we enforce that flags are passed through // revert data as to retrieve execution metadata that would normally be reverted out of // existence. bool success; bytes memory returndata; if (_isCreate) { // safeCREATE() is a function which replicates a CREATE message, but uses return values // Which match that of CALL (i.e. bool, bytes). This allows many security checks to be // to be shared between untrusted call and create call frames. (success, returndata) = address(this).call( abi.encodeWithSelector( this.safeCREATE.selector, _gasLimit, _data, _contract ) ); } else { (success, returndata) = _contract.call{gas: _gasLimit}(_data); } // Switch back to the original message context now that we're out of the call. _switchMessageContext(_nextMessageContext, prevMessageContext); // Assuming there were no reverts, the message record should be accurate here. We'll update // this value in the case of a revert. uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft; // Reverts at this point are completely OK, but we need to make a few updates based on the // information passed through the revert. if (success == false) { ( RevertFlag flag, uint256 nuisanceGasLeftPostRevert, uint256 ovmGasRefund, bytes memory returndataFromFlag ) = _decodeRevertData(returndata); // INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the // parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must // halt any further transaction execution that could impact the execution result. if (flag == RevertFlag.INVALID_STATE_ACCESS) { _revertWithFlag(flag); } // INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't // dependent on the input state, so we can just handle them like standard reverts. Our only change here // is to record the gas refund reported by the call (enforced by safety checking). if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE || flag == RevertFlag.STATIC_VIOLATION || flag == RevertFlag.CREATOR_NOT_ALLOWED ) { transactionRecord.ovmGasRefund = ovmGasRefund; } // INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the // flag, *not* the full encoded flag. All other revert types return no data. if ( flag == RevertFlag.INTENTIONAL_REVERT || _isCreate ) { returndata = returndataFromFlag; } else { returndata = hex''; } // Reverts mean we need to use up whatever "nuisance gas" was used by the call. // EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message // to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they // run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags // will simply pass up the remaining nuisance gas. nuisanceGasLeft = nuisanceGasLeftPostRevert; } // We need to reset the nuisance gas back to its original value minus the amount used here. messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft); return ( success, returndata ); } /** * Handles the creation-specific safety measures required for OVM contract deployment. * This function sanitizes the return types for creation messages to match calls (bool, bytes), * by being an external function which the EM can call, that mimics the success/fail case of the CREATE. * This allows for consistent handling of both types of messages in _handleExternalMessage(). * Having this step occur as a separate call frame also allows us to easily revert the * contract deployment in the event that the code is unsafe. * * @param _gasLimit Amount of gas to be passed into this creation. * @param _creationCode Code to pass into CREATE for deployment. * @param _address OVM address being deployed to. */ function safeCREATE( uint _gasLimit, bytes memory _creationCode, address _address ) external { // The only way this should callable is from within _createContract(), // and it should DEFINITELY not be callable by a non-EM code contract. if (msg.sender != address(this)) { return; } // Check that there is not already code at this address. if (_hasEmptyAccount(_address) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.CREATE_COLLISION, Lib_ErrorUtils.encodeRevertString("A contract has already been deployed to this address") ); } // Check the creation bytecode against the OVM_SafetyChecker. if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?") ); } // We always need to initialize the contract with the default account values. _initPendingAccount(_address); // Actually execute the EVM create message. // NOTE: The inline assembly below means we can NOT make any evm calls between here and then. address ethAddress = Lib_EthUtils.createContract(_creationCode); if (ethAddress == address(0)) { // If the creation fails, the EVM lets us grab its revert data. This may contain a revert flag // to be used above in _handleExternalMessage, so we pass the revert data back up unmodified. assembly { returndatacopy(0,0,returndatasize()) revert(0, returndatasize()) } } // Again simply checking that the deployed code is safe too. Contracts can generate // arbitrary deployment code, so there's no easy way to analyze this beforehand. bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress); if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.") ); } // Contract creation didn't need to be reverted and the bytecode is safe. We finish up by // associating the desired address with the newly created contract's code hash and address. _commitPendingAccount( _address, ethAddress, Lib_EthUtils.getCodeHash(ethAddress) ); } /****************************************** * Internal Functions: State Manipulation * ******************************************/ /** * Checks whether an account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account exists. */ function _hasAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasAccount(_address); } /** * Checks whether a known empty account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account empty exists. */ function _hasEmptyAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasEmptyAccount(_address); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function _setAccountNonce( address _address, uint256 _nonce ) internal { _checkAccountChange(_address); ovmStateManager.setAccountNonce(_address, _nonce); } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return _nonce Nonce of the account. */ function _getAccountNonce( address _address ) internal returns ( uint256 _nonce ) { _checkAccountLoad(_address); return ovmStateManager.getAccountNonce(_address); } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return _ethAddress Corresponding Ethereum address. */ function _getAccountEthAddress( address _address ) internal returns ( address _ethAddress ) { _checkAccountLoad(_address); return ovmStateManager.getAccountEthAddress(_address); } /** * Creates the default account object for the given address. * @param _address Address of the account create. */ function _initPendingAccount( address _address ) internal { // Although it seems like `_checkAccountChange` would be more appropriate here, we don't // actually consider an account "changed" until it's inserted into the state (in this case // by `_commitPendingAccount`). _checkAccountLoad(_address); ovmStateManager.initPendingAccount(_address); } /** * Stores additional relevant data for a new account, thereby "committing" it to the state. * This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract * creation. * @param _address Address of the account to commit. * @param _ethAddress Address of the associated deployed contract. * @param _codeHash Hash of the code stored at the address. */ function _commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) internal { _checkAccountChange(_address); ovmStateManager.commitPendingAccount( _address, _ethAddress, _codeHash ); } /** * Retrieves the value of a storage slot. * @param _contract Address of the contract to query. * @param _key 32 byte key of the storage slot. * @return _value 32 byte storage slot value. */ function _getContractStorage( address _contract, bytes32 _key ) internal returns ( bytes32 _value ) { _checkContractStorageLoad(_contract, _key); return ovmStateManager.getContractStorage(_contract, _key); } /** * Sets the value of a storage slot. * @param _contract Address of the contract to modify. * @param _key 32 byte key of the storage slot. * @param _value 32 byte storage slot value. */ function _putContractStorage( address _contract, bytes32 _key, bytes32 _value ) internal { // We don't set storage if the value didn't change. Although this acts as a convenient // optimization, it's also necessary to avoid the case in which a contract with no storage // attempts to store the value "0" at any key. Putting this value (and therefore requiring // that the value be committed into the storage trie after execution) would incorrectly // modify the storage root. if (_getContractStorage(_contract, _key) == _value) { return; } _checkContractStorageChange(_contract, _key); ovmStateManager.putContractStorage(_contract, _key, _value); } /** * Validation whenever a contract needs to be loaded. Checks that the account exists, charges * nuisance gas if the account hasn't been loaded before. * @param _address Address of the account to load. */ function _checkAccountLoad( address _address ) internal { // See `_checkContractStorageLoad` for more information. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // See `_checkContractStorageLoad` for more information. if (ovmStateManager.hasAccount(_address) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the account has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that an account is loaded. ( bool _wasAccountAlreadyLoaded ) = ovmStateManager.testAndSetAccountLoaded(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyLoaded == false) { _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a contract needs to be changed. Checks that the account exists, charges * nuisance gas if the account hasn't been changed before. * @param _address Address of the account to change. */ function _checkAccountChange( address _address ) internal { // Start by checking for a load as we only want to charge nuisance gas proportional to // contract size once. _checkAccountLoad(_address); // Check whether the account has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that an account is changed. ( bool _wasAccountAlreadyChanged ) = ovmStateManager.testAndSetAccountChanged(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyChanged == false) { ovmStateManager.incrementTotalUncommittedAccounts(); _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a slot needs to be loaded. Checks that the account exists, charges * nuisance gas if the slot hasn't been loaded before. * @param _contract Address of the account to load from. * @param _key 32 byte key to load. */ function _checkContractStorageLoad( address _contract, bytes32 _key ) internal { // Another case of hidden complexity. If we didn't enforce this requirement, then a // contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail // on L1 but not on L2. A contract could use this behavior to prevent the // OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS // allows us to also charge for the full message nuisance gas, because you deserve that for // trying to break the contract in this way. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // We need to make sure that the transaction isn't trying to access storage that hasn't // been provided to the OVM_StateManager. We'll immediately abort if this is the case. // We know that we have enough gas to do this check because of the above test. if (ovmStateManager.hasContractStorage(_contract, _key) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the slot has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that a slot is loaded. ( bool _wasContractStorageAlreadyLoaded ) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key); // If we hadn't already loaded the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyLoaded == false) { _useNuisanceGas(NUISANCE_GAS_SLOAD); } } /** * Validation whenever a slot needs to be changed. Checks that the account exists, charges * nuisance gas if the slot hasn't been changed before. * @param _contract Address of the account to change. * @param _key 32 byte key to change. */ function _checkContractStorageChange( address _contract, bytes32 _key ) internal { // Start by checking for load to make sure we have the storage slot and that we charge the // "nuisance gas" necessary to prove the storage slot state. _checkContractStorageLoad(_contract, _key); // Check whether the slot has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that a slot is changed. ( bool _wasContractStorageAlreadyChanged ) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key); // If we hadn't already changed the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyChanged == false) { // Changing a storage slot means that we're also going to have to change the // corresponding account, so do an account change check. _checkAccountChange(_contract); ovmStateManager.incrementTotalUncommittedContractStorage(); _useNuisanceGas(NUISANCE_GAS_SSTORE); } } /************************************ * Internal Functions: Revert Logic * ************************************/ /** * Simple encoding for revert data. * @param _flag Flag to revert with. * @param _data Additional user-provided revert data. * @return _revertdata Encoded revert data. */ function _encodeRevertData( RevertFlag _flag, bytes memory _data ) internal view returns ( bytes memory _revertdata ) { // Out of gas and create exceptions will fundamentally return no data, so simulating it shouldn't either. if ( _flag == RevertFlag.OUT_OF_GAS ) { return bytes(''); } // INVALID_STATE_ACCESS doesn't need to return any data other than the flag. if (_flag == RevertFlag.INVALID_STATE_ACCESS) { return abi.encode( _flag, 0, 0, bytes('') ); } // Just ABI encode the rest of the parameters. return abi.encode( _flag, messageRecord.nuisanceGasLeft, transactionRecord.ovmGasRefund, _data ); } /** * Simple decoding for revert data. * @param _revertdata Revert data to decode. * @return _flag Flag used to revert. * @return _nuisanceGasLeft Amount of nuisance gas unused by the message. * @return _ovmGasRefund Amount of gas refunded during the message. * @return _data Additional user-provided revert data. */ function _decodeRevertData( bytes memory _revertdata ) internal pure returns ( RevertFlag _flag, uint256 _nuisanceGasLeft, uint256 _ovmGasRefund, bytes memory _data ) { // A length of zero means the call ran out of gas, just return empty data. if (_revertdata.length == 0) { return ( RevertFlag.OUT_OF_GAS, 0, 0, bytes('') ); } // ABI decode the incoming data. return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes)); } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. * @param _data Additional user-provided data. */ function _revertWithFlag( RevertFlag _flag, bytes memory _data ) internal view { bytes memory revertdata = _encodeRevertData( _flag, _data ); assembly { revert(add(revertdata, 0x20), mload(revertdata)) } } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. */ function _revertWithFlag( RevertFlag _flag ) internal { _revertWithFlag(_flag, bytes('')); } /****************************************** * Internal Functions: Nuisance Gas Logic * ******************************************/ /** * Computes the nuisance gas limit from the gas limit. * @dev This function is currently using a naive implementation whereby the nuisance gas limit * is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that * this implementation is perfectly fine, but we may change this formula later. * @param _gasLimit Gas limit to compute from. * @return _nuisanceGasLimit Computed nuisance gas limit. */ function _getNuisanceGasLimit( uint256 _gasLimit ) internal view returns ( uint256 _nuisanceGasLimit ) { return _gasLimit < gasleft() ? _gasLimit : gasleft(); } /** * Uses a certain amount of nuisance gas. * @param _amount Amount of nuisance gas to use. */ function _useNuisanceGas( uint256 _amount ) internal { // Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas // refund to be given at the end of the transaction. if (messageRecord.nuisanceGasLeft < _amount) { _revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS); } messageRecord.nuisanceGasLeft -= _amount; } /************************************ * Internal Functions: Gas Metering * ************************************/ /** * Checks whether a transaction needs to start a new epoch and does so if necessary. * @param _timestamp Transaction timestamp. */ function _checkNeedsNewEpoch( uint256 _timestamp ) internal { if ( _timestamp >= ( _getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP) + gasMeterConfig.secondsPerEpoch ) ) { _putGasMetadata( GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP, _timestamp ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS ) ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS ) ); } } /** * Validates the input values of a transaction. * @return _valid Whether or not the transaction data is valid. */ function _isValidInput( Lib_OVMCodec.Transaction memory _transaction ) view internal returns ( bool ) { // Prevent reentrancy to run(): // This check prevents calling run with the default ovmNumber. // Combined with the first check in run(): // if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // It should be impossible to re-enter since run() returns before any other call frames are created. // Since this value is already being written to storage, we save much gas compared to // using the standard nonReentrant pattern. if (_transaction.blockNumber == DEFAULT_UINT256) { return false; } if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) { return false; } return true; } /** * Validates the gas limit for a given transaction. * @param _gasLimit Gas limit provided by the transaction. * param _queueOrigin Queue from which the transaction originated. * @return _valid Whether or not the gas limit is valid. */ function _isValidGasLimit( uint256 _gasLimit, Lib_OVMCodec.QueueOrigin // _queueOrigin ) view internal returns ( bool _valid ) { // Always have to be below the maximum gas limit. if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) { return false; } // Always have to be above the minimum gas limit. if (_gasLimit < gasMeterConfig.minTransactionGasLimit) { return false; } // TEMPORARY: Gas metering is disabled for minnet. return true; // GasMetadataKey cumulativeGasKey; // GasMetadataKey prevEpochGasKey; // if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS; // } else { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS; // } // return ( // ( // _getGasMetadata(cumulativeGasKey) // - _getGasMetadata(prevEpochGasKey) // + _gasLimit // ) < gasMeterConfig.maxGasPerQueuePerEpoch // ); } /** * Updates the cumulative gas after a transaction. * @param _gasUsed Gas used by the transaction. * @param _queueOrigin Queue from which the transaction originated. */ function _updateCumulativeGas( uint256 _gasUsed, Lib_OVMCodec.QueueOrigin _queueOrigin ) internal { GasMetadataKey cumulativeGasKey; if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; } else { cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; } _putGasMetadata( cumulativeGasKey, ( _getGasMetadata(cumulativeGasKey) + gasMeterConfig.minTransactionGasLimit + _gasUsed - transactionRecord.ovmGasRefund ) ); } /** * Retrieves the value of a gas metadata key. * @param _key Gas metadata key to retrieve. * @return _value Value stored at the given key. */ function _getGasMetadata( GasMetadataKey _key ) internal returns ( uint256 _value ) { return uint256(_getContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)) )); } /** * Sets the value of a gas metadata key. * @param _key Gas metadata key to set. * @param _value Value to store at the given key. */ function _putGasMetadata( GasMetadataKey _key, uint256 _value ) internal { _putContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)), bytes32(uint256(_value)) ); } /***************************************** * Internal Functions: Execution Context * *****************************************/ /** * Swaps over to a new message context. * @param _prevMessageContext Context we're switching from. * @param _nextMessageContext Context we're switching to. */ function _switchMessageContext( MessageContext memory _prevMessageContext, MessageContext memory _nextMessageContext ) internal { // Avoid unnecessary the SSTORE. if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) { messageContext.ovmCALLER = _nextMessageContext.ovmCALLER; } // Avoid unnecessary the SSTORE. if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) { messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS; } // Avoid unnecessary the SSTORE. if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) { messageContext.isStatic = _nextMessageContext.isStatic; } } /** * Initializes the execution context. * @param _transaction OVM transaction being executed. */ function _initContext( Lib_OVMCodec.Transaction memory _transaction ) internal { transactionContext.ovmTIMESTAMP = _transaction.timestamp; transactionContext.ovmNUMBER = _transaction.blockNumber; transactionContext.ovmTXGASLIMIT = _transaction.gasLimit; transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin; transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin; transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch; messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit); } /** * Resets the transaction and message context. */ function _resetContext() internal { transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS; transactionContext.ovmTIMESTAMP = DEFAULT_UINT256; transactionContext.ovmNUMBER = DEFAULT_UINT256; transactionContext.ovmGASLIMIT = DEFAULT_UINT256; transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256; transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE; transactionRecord.ovmGasRefund = DEFAULT_UINT256; messageContext.ovmCALLER = DEFAULT_ADDRESS; messageContext.ovmADDRESS = DEFAULT_ADDRESS; messageContext.isStatic = false; messageRecord.nuisanceGasLeft = DEFAULT_UINT256; // Reset the ovmStateManager. ovmStateManager = iOVM_StateManager(address(0)); } /***************************** * L2-only Helper Functions * *****************************/ /** * Unreachable helper function for simulating eth_calls with an OVM message context. * This function will throw an exception in all cases other than when used as a custom entrypoint in L2 Geth to simulate eth_call. * @param _transaction the message transaction to simulate. * @param _from the OVM account the simulated call should be from. */ function simulateMessage( Lib_OVMCodec.Transaction memory _transaction, address _from, iOVM_StateManager _ovmStateManager ) external returns ( bool, bytes memory ) { // Prevent this call from having any effect unless in a custom-set VM frame require(msg.sender == address(0)); ovmStateManager = _ovmStateManager; _initContext(_transaction); messageRecord.nuisanceGasLeft = uint(-1); messageContext.ovmADDRESS = _from; bool isCreate = _transaction.entrypoint == address(0); if (isCreate) { (address created, bytes memory revertData) = ovmCREATE(_transaction.data); if (created == address(0)) { return (false, revertData); } else { // The eth_call RPC endpoint for to = undefined will return the deployed bytecode // in the success case, differing from standard create messages. return (true, Lib_EthUtils.getCode(created)); } } else { return ovmCALL( _transaction.gasLimit, _transaction.entrypoint, _transaction.data ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; /* Interface Imports */ import { iOVM_DeployerWhitelist } from "../../iOVM/predeploys/iOVM_DeployerWhitelist.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title OVM_DeployerWhitelist * @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the * initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts * which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an * ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted. * * Compiler used: solc * Runtime target: OVM */ contract OVM_DeployerWhitelist is iOVM_DeployerWhitelist { /********************** * Contract Constants * **********************/ bytes32 internal constant KEY_INITIALIZED = 0x0000000000000000000000000000000000000000000000000000000000000010; bytes32 internal constant KEY_OWNER = 0x0000000000000000000000000000000000000000000000000000000000000011; bytes32 internal constant KEY_ALLOW_ARBITRARY_DEPLOYMENT = 0x0000000000000000000000000000000000000000000000000000000000000012; /********************** * Function Modifiers * **********************/ /** * Blocks functions to anyone except the contract owner. */ modifier onlyOwner() { address owner = Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( KEY_OWNER ) ); Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_SafeExecutionManagerWrapper.safeCALLER() == owner, "Function can only be called by the owner of this contract." ); _; } /******************** * Public Functions * ********************/ /** * Initializes the whitelist. * @param _owner Address of the owner for this contract. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function initialize( address _owner, bool _allowArbitraryDeployment ) override public { bool initialized = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED) ); if (initialized == true) { return; } Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_INITIALIZED, Lib_Bytes32Utils.fromBool(true) ); Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_OWNER, Lib_Bytes32Utils.fromAddress(_owner) ); Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_ALLOW_ARBITRARY_DEPLOYMENT, Lib_Bytes32Utils.fromBool(_allowArbitraryDeployment) ); } /** * Gets the owner of the whitelist. */ function getOwner() override public returns( address ) { return Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( KEY_OWNER ) ); } /** * Adds or removes an address from the deployment whitelist. * @param _deployer Address to update permissions for. * @param _isWhitelisted Whether or not the address is whitelisted. */ function setWhitelistedDeployer( address _deployer, bool _isWhitelisted ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( Lib_Bytes32Utils.fromAddress(_deployer), Lib_Bytes32Utils.fromBool(_isWhitelisted) ); } /** * Updates the owner of this contract. * @param _owner Address of the new owner. */ function setOwner( address _owner ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_OWNER, Lib_Bytes32Utils.fromAddress(_owner) ); } /** * Updates the arbitrary deployment flag. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function setAllowArbitraryDeployment( bool _allowArbitraryDeployment ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_ALLOW_ARBITRARY_DEPLOYMENT, Lib_Bytes32Utils.fromBool(_allowArbitraryDeployment) ); } /** * Permanently enables arbitrary contract deployment and deletes the owner. */ function enableArbitraryContractDeployment() override public onlyOwner { setAllowArbitraryDeployment(true); setOwner(address(0)); } /** * Checks whether an address is allowed to deploy contracts. * @param _deployer Address to check. * @return _allowed Whether or not the address can deploy contracts. */ function isDeployerAllowed( address _deployer ) override public returns ( bool _allowed ) { bool initialized = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED) ); if (initialized == false) { return true; } bool allowArbitraryDeployment = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_ALLOW_ARBITRARY_DEPLOYMENT) ); if (allowArbitraryDeployment == true) { return true; } bool isWhitelisted = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD( Lib_Bytes32Utils.fromAddress(_deployer) ) ); return isWhitelisted; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_ECDSAContractAccount */ interface iOVM_ECDSAContractAccount { /******************** * Public Functions * ********************/ function execute( bytes memory _transaction, Lib_OVMCodec.EOASignatureType _signatureType, uint8 _v, bytes32 _r, bytes32 _s ) external returns (bool _success, bytes memory _returndata); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; interface iOVM_ExecutionManager { /********** * Enums * *********/ enum RevertFlag { OUT_OF_GAS, INTENTIONAL_REVERT, EXCEEDS_NUISANCE_GAS, INVALID_STATE_ACCESS, UNSAFE_BYTECODE, CREATE_COLLISION, STATIC_VIOLATION, CREATOR_NOT_ALLOWED } enum GasMetadataKey { CURRENT_EPOCH_START_TIMESTAMP, CUMULATIVE_SEQUENCER_QUEUE_GAS, CUMULATIVE_L1TOL2_QUEUE_GAS, PREV_EPOCH_SEQUENCER_QUEUE_GAS, PREV_EPOCH_L1TOL2_QUEUE_GAS } /*********** * Structs * ***********/ struct GasMeterConfig { uint256 minTransactionGasLimit; uint256 maxTransactionGasLimit; uint256 maxGasPerQueuePerEpoch; uint256 secondsPerEpoch; } struct GlobalContext { uint256 ovmCHAINID; } struct TransactionContext { Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN; uint256 ovmTIMESTAMP; uint256 ovmNUMBER; uint256 ovmGASLIMIT; uint256 ovmTXGASLIMIT; address ovmL1TXORIGIN; } struct TransactionRecord { uint256 ovmGasRefund; } struct MessageContext { address ovmCALLER; address ovmADDRESS; bool isStatic; } struct MessageRecord { uint256 nuisanceGasLeft; } /************************************ * Transaction Execution Entrypoint * ************************************/ function run( Lib_OVMCodec.Transaction calldata _transaction, address _txStateManager ) external; /******************* * Context Opcodes * *******************/ function ovmCALLER() external view returns (address _caller); function ovmADDRESS() external view returns (address _address); function ovmTIMESTAMP() external view returns (uint256 _timestamp); function ovmNUMBER() external view returns (uint256 _number); function ovmGASLIMIT() external view returns (uint256 _gasLimit); function ovmCHAINID() external view returns (uint256 _chainId); /********************** * L2 Context Opcodes * **********************/ function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin); function ovmL1TXORIGIN() external view returns (address _l1TxOrigin); /******************* * Halting Opcodes * *******************/ function ovmREVERT(bytes memory _data) external; /***************************** * Contract Creation Opcodes * *****************************/ function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata); function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata); /******************************* * Account Abstraction Opcodes * ******************************/ function ovmGETNONCE() external returns (uint256 _nonce); function ovmINCREMENTNONCE() external; function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external; /**************************** * Contract Calling Opcodes * ****************************/ function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); /**************************** * Contract Storage Opcodes * ****************************/ function ovmSLOAD(bytes32 _key) external returns (bytes32 _value); function ovmSSTORE(bytes32 _key, bytes32 _value) external; /************************* * Contract Code Opcodes * *************************/ function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code); function ovmEXTCODESIZE(address _contract) external returns (uint256 _size); function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash); /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_SafetyChecker */ interface iOVM_SafetyChecker { /******************** * Public Functions * ********************/ function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateManager */ interface iOVM_StateManager { /******************* * Data Structures * *******************/ enum ItemState { ITEM_UNTOUCHED, ITEM_LOADED, ITEM_CHANGED, ITEM_COMMITTED } /*************************** * Public Functions: Misc * ***************************/ function isAuthenticated(address _address) external view returns (bool); /*************************** * Public Functions: Setup * ***************************/ function owner() external view returns (address _owner); function ovmExecutionManager() external view returns (address _ovmExecutionManager); function setExecutionManager(address _ovmExecutionManager) external; /************************************ * Public Functions: Account Access * ************************************/ function putAccount(address _address, Lib_OVMCodec.Account memory _account) external; function putEmptyAccount(address _address) external; function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account); function hasAccount(address _address) external view returns (bool _exists); function hasEmptyAccount(address _address) external view returns (bool _exists); function setAccountNonce(address _address, uint256 _nonce) external; function getAccountNonce(address _address) external view returns (uint256 _nonce); function getAccountEthAddress(address _address) external view returns (address _ethAddress); function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot); function initPendingAccount(address _address) external; function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external; function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded); function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged); function commitAccount(address _address) external returns (bool _wasAccountCommitted); function incrementTotalUncommittedAccounts() external; function getTotalUncommittedAccounts() external view returns (uint256 _total); function wasAccountChanged(address _address) external view returns (bool); function wasAccountCommitted(address _address) external view returns (bool); /************************************ * Public Functions: Storage Access * ************************************/ function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external; function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value); function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists); function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded); function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged); function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted); function incrementTotalUncommittedContractStorage() external; function getTotalUncommittedContractStorage() external view returns (uint256 _total); function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool); function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_DeployerWhitelist */ interface iOVM_DeployerWhitelist { /******************** * Public Functions * ********************/ function initialize(address _owner, bool _allowArbitraryDeployment) external; function getOwner() external returns (address _owner); function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external; function setOwner(address _newOwner) external; function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external; function enableArbitraryContractDeployment() external; function isDeployerAllowed(address _deployer) external returns (bool _allowed); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum EOASignatureType { EIP155_TRANSACTION, ETH_SIGNED_MESSAGE } enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } struct EIP155Transaction { uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; uint256 chainId; } /********************** * Internal Functions * **********************/ /** * Decodes an EOA transaction (i.e., native Ethereum RLP encoding). * @param _transaction Encoded EOA transaction. * @return Transaction decoded into a struct. */ function decodeEIP155Transaction( bytes memory _transaction, bool _isEthSignedMessage ) internal pure returns ( EIP155Transaction memory ) { if (_isEthSignedMessage) { ( uint256 _nonce, uint256 _gasLimit, uint256 _gasPrice, uint256 _chainId, address _to, bytes memory _data ) = abi.decode( _transaction, (uint256, uint256, uint256, uint256, address ,bytes) ); return EIP155Transaction({ nonce: _nonce, gasPrice: _gasPrice, gasLimit: _gasLimit, to: _to, value: 0, data: _data, chainId: _chainId }); } else { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_transaction); return EIP155Transaction({ nonce: Lib_RLPReader.readUint256(decoded[0]), gasPrice: Lib_RLPReader.readUint256(decoded[1]), gasLimit: Lib_RLPReader.readUint256(decoded[2]), to: Lib_RLPReader.readAddress(decoded[3]), value: Lib_RLPReader.readUint256(decoded[4]), data: Lib_RLPReader.readBytes(decoded[5]), chainId: Lib_RLPReader.readUint256(decoded[6]) }); } } /** * Decompresses a compressed EIP155 transaction. * @param _transaction Compressed EIP155 transaction bytes. * @return Transaction parsed into a struct. */ function decompressEIP155Transaction( bytes memory _transaction ) internal returns ( EIP155Transaction memory ) { return EIP155Transaction({ gasLimit: Lib_BytesUtils.toUint24(_transaction, 0), gasPrice: uint256(Lib_BytesUtils.toUint24(_transaction, 3)) * 1000000, nonce: Lib_BytesUtils.toUint24(_transaction, 6), to: Lib_BytesUtils.toAddress(_transaction, 9), data: Lib_BytesUtils.slice(_transaction, 29), chainId: Lib_SafeExecutionManagerWrapper.safeCHAINID(), value: 0 }); } /** * Encodes an EOA transaction back into the original transaction. * @param _transaction EIP155transaction to encode. * @param _isEthSignedMessage Whether or not this was an eth signed message. * @return Encoded transaction. */ function encodeEIP155Transaction( EIP155Transaction memory _transaction, bool _isEthSignedMessage ) internal pure returns ( bytes memory ) { if (_isEthSignedMessage) { return abi.encode( _transaction.nonce, _transaction.gasLimit, _transaction.gasPrice, _transaction.chainId, _transaction.to, _transaction.data ); } else { bytes[] memory raw = new bytes[](9); raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce); raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice); raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit); if (_transaction.to == address(0)) { raw[3] = Lib_RLPWriter.writeBytes(''); } else { raw[3] = Lib_RLPWriter.writeAddress(_transaction.to); } raw[4] = Lib_RLPWriter.writeUint(0); raw[5] = Lib_RLPWriter.writeBytes(_transaction.data); raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId); raw[7] = Lib_RLPWriter.writeBytes(bytes('')); raw[8] = Lib_RLPWriter.writeBytes(bytes('')); return Lib_RLPWriter.writeList(raw); } } /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction( Transaction memory _transaction ) internal pure returns ( bytes memory ) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction( Transaction memory _transaction ) internal pure returns ( bytes32 ) { return keccak256(encodeTransaction(_transaction)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { Ownable } from "./Lib_Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string _name, address _newAddress ); /******************************************* * Contract Variables: Internal Accounting * *******************************************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ function setAddress( string memory _name, address _address ) public onlyOwner { emit AddressSet(_name, _address); addresses[_getNameHash(_name)] = _address; } function getAddress( string memory _name ) public view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ function _getNameHash( string memory _name ) internal pure returns ( bytes32 _hash ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /******************************************* * Contract Variables: Contract References * *******************************************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ function resolve( string memory _name ) public view returns ( address _contract ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Ownable * @dev Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol */ abstract contract Ownable { /************* * Variables * *************/ address public owner; /********** * Events * **********/ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /*************** * Constructor * ***************/ constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require( owner == msg.sender, "Ownable: caller is not the owner" ); _; } /******************** * Public Functions * ********************/ 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 cannot be the zero address" ); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem( bytes memory _in ) internal pure returns ( RLPItem memory ) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( RLPItem memory _in ) internal pure returns ( RLPItem[] memory ) { ( uint256 listOffset, , RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value." ); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length." ); ( uint256 itemOffset, uint256 itemLength, ) = _decodeLength(RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( bytes memory _in ) internal pure returns ( RLPItem[] memory ) { return readList( toRLPItem(_in) ); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value." ); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( bytes memory _in ) internal pure returns ( bytes memory ) { return readBytes( toRLPItem(_in) ); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( RLPItem memory _in ) internal pure returns ( string memory ) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( bytes memory _in ) internal pure returns ( string memory ) { return readString( toRLPItem(_in) ); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( RLPItem memory _in ) internal pure returns ( bytes32 ) { require( _in.length <= 33, "Invalid RLP bytes32 value." ); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value." ); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( bytes memory _in ) internal pure returns ( bytes32 ) { return readBytes32( toRLPItem(_in) ); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( RLPItem memory _in ) internal pure returns ( uint256 ) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( bytes memory _in ) internal pure returns ( uint256 ) { return readUint256( toRLPItem(_in) ); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( RLPItem memory _in ) internal pure returns ( bool ) { require( _in.length == 1, "Invalid RLP boolean value." ); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1" ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( RLPItem memory _in ) internal pure returns ( address ) { if (_in.length == 1) { return address(0); } require( _in.length == 21, "Invalid RLP address value." ); return address(readUint256(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( bytes memory _in ) internal pure returns ( address ) { return readAddress( toRLPItem(_in) ); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength( RLPItem memory _in ) private pure returns ( uint256, uint256, RLPItemType ) { require( _in.length > 0, "RLP item cannot be null." ); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require( _in.length > strLen, "Invalid RLP short string." ); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require( _in.length > lenOfStrLen, "Invalid RLP long string length." ); uint256 strLen; assembly { // Pick out the string length. strLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)) ) } require( _in.length > lenOfStrLen + strLen, "Invalid RLP long string." ); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require( _in.length > listLen, "Invalid RLP short list." ); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require( _in.length > lenOfListLen, "Invalid RLP long list length." ); uint256 listLen; assembly { // Pick out the list length. listLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)) ) } require( _in.length > lenOfListLen + listLen, "Invalid RLP long list." ); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns ( bytes memory ) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return _out The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory _out ) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return _out The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory _out ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return _out The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory _out ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return _out The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return _out The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return _out The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory _out ) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return _encoded RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory _encoded ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return _binary RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory _binary ) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return _flattened The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory _flattened ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool( bytes32 _in ) internal pure returns ( bool ) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool( bool _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress( bytes32 _in ) internal pure returns ( address ) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress( address _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice( bytes memory _bytes, uint256 _start ) internal pure returns (bytes memory) { if (_bytes.length - _start == 0) { return bytes(''); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns (bytes32) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } function toBytes32( bytes memory _bytes ) internal pure returns (bytes32) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes } function toUint256( bytes memory _bytes ) internal pure returns (uint256) { return uint256(toBytes32(_bytes)); } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, "toUint24_overflow"); require(_bytes.length >= _start + 3 , "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toNibbles( bytes memory _bytes ) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_ECDSAUtils */ library Lib_ECDSAUtils { /************************************** * Internal Functions: ECDSA Recovery * **************************************/ /** * Recovers a signed address given a message and signature. * @param _message Message that was originally signed. * @param _isEthSignedMessage Whether or not the user used the `Ethereum Signed Message` prefix. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. * @return _sender Signer address. */ function recover( bytes memory _message, bool _isEthSignedMessage, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns ( address _sender ) { bytes32 messageHash = getMessageHash(_message, _isEthSignedMessage); return ecrecover( messageHash, _v + 27, _r, _s ); } function getMessageHash( bytes memory _message, bool _isEthSignedMessage ) internal pure returns (bytes32) { if (_isEthSignedMessage) { return getEthSignedMessageHash(_message); } return getNativeMessageHash(_message); } /************************************* * Private Functions: ECDSA Recovery * *************************************/ /** * Gets the native message hash (simple keccak256) for a message. * @param _message Message to hash. * @return _messageHash Native message hash. */ function getNativeMessageHash( bytes memory _message ) private pure returns ( bytes32 _messageHash ) { return keccak256(_message); } /** * Gets the hash of a message with the `Ethereum Signed Message` prefix. * @param _message Message to hash. * @return _messageHash Prefixed message hash. */ function getEthSignedMessageHash( bytes memory _message ) private pure returns ( bytes32 _messageHash ) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 messageHash = keccak256(_message); return keccak256(abi.encodePacked(prefix, messageHash)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_ErrorUtils */ library Lib_ErrorUtils { /********************** * Internal Functions * **********************/ /** * Encodes an error string into raw solidity-style revert data. * (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))")) * Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)#panic-via-assert-and-error-via-require * @param _reason Reason for the reversion. * @return Standard solidity revert data for the given reason. */ function encodeRevertString( string memory _reason ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "Error(string)", _reason ); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol"; /** * @title Lib_EthUtils */ library Lib_EthUtils { /*********************************** * Internal Functions: Code Access * ***********************************/ /** * Gets the code for a given address. * @param _address Address to get code for. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return _code Code read from the contract. */ function getCode( address _address, uint256 _offset, uint256 _length ) internal view returns ( bytes memory _code ) { assembly { _code := mload(0x40) mstore(0x40, add(_code, add(_length, 0x20))) mstore(_code, _length) extcodecopy(_address, add(_code, 0x20), _offset, _length) } return _code; } /** * Gets the full code for a given address. * @param _address Address to get code for. * @return _code Full code of the contract. */ function getCode( address _address ) internal view returns ( bytes memory _code ) { return getCode( _address, 0, getCodeSize(_address) ); } /** * Gets the size of a contract's code in bytes. * @param _address Address to get code size for. * @return _codeSize Size of the contract's code in bytes. */ function getCodeSize( address _address ) internal view returns ( uint256 _codeSize ) { assembly { _codeSize := extcodesize(_address) } return _codeSize; } /** * Gets the hash of a contract's code. * @param _address Address to get a code hash for. * @return _codeHash Hash of the contract's code. */ function getCodeHash( address _address ) internal view returns ( bytes32 _codeHash ) { assembly { _codeHash := extcodehash(_address) } return _codeHash; } /***************************************** * Internal Functions: Contract Creation * *****************************************/ /** * Creates a contract with some given initialization code. * @param _code Contract initialization code. * @return _created Address of the created contract. */ function createContract( bytes memory _code ) internal returns ( address _created ) { assembly { _created := create( 0, add(_code, 0x20), mload(_code) ) } return _created; } /** * Computes the address that would be generated by CREATE. * @param _creator Address creating the contract. * @param _nonce Creator's nonce. * @return _address Address to be generated by CREATE. */ function getAddressForCREATE( address _creator, uint256 _nonce ) internal pure returns ( address _address ) { bytes[] memory encoded = new bytes[](2); encoded[0] = Lib_RLPWriter.writeAddress(_creator); encoded[1] = Lib_RLPWriter.writeUint(_nonce); bytes memory encodedList = Lib_RLPWriter.writeList(encoded); return Lib_Bytes32Utils.toAddress(keccak256(encodedList)); } /** * Computes the address that would be generated by CREATE2. * @param _creator Address creating the contract. * @param _bytecode Bytecode of the contract to be created. * @param _salt 32 byte salt value mixed into the hash. * @return _address Address to be generated by CREATE2. */ function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) internal pure returns (address _address) { bytes32 hashedData = keccak256(abi.encodePacked( byte(0xff), _creator, _salt, keccak256(_bytecode) )); return Lib_Bytes32Utils.toAddress(hashedData); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; /** * @title Lib_SafeExecutionManagerWrapper * @dev The Safe Execution Manager Wrapper provides functions which facilitate writing OVM safe * code using the standard solidity compiler, by routing all its operations through the Execution * Manager. * * Compiler used: solc * Runtime target: OVM */ library Lib_SafeExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCALL. * @param _gasLimit Gas limit for the call. * @param _target Address to call. * @param _calldata Data to send to the call. * @return _success Whether or not the call reverted. * @return _returndata Data returned by the call. */ function safeCALL( uint256 _gasLimit, address _target, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCALL(uint256,address,bytes)", _gasLimit, _target, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Performs a safe ovmDELEGATECALL. * @param _gasLimit Gas limit for the call. * @param _target Address to call. * @param _calldata Data to send to the call. * @return _success Whether or not the call reverted. * @return _returndata Data returned by the call. */ function safeDELEGATECALL( uint256 _gasLimit, address _target, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmDELEGATECALL(uint256,address,bytes)", _gasLimit, _target, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Performs a safe ovmCREATE call. * @param _gasLimit Gas limit for the creation. * @param _bytecode Code for the new contract. * @return _contract Address of the created contract. */ function safeCREATE( uint256 _gasLimit, bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _safeExecutionManagerInteraction( _gasLimit, abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmEXTCODESIZE call. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function safeEXTCODESIZE( address _contract ) internal returns ( uint256 _EXTCODESIZE ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmEXTCODESIZE(address)", _contract ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmCHAINID call. * @return _CHAINID Result of calling ovmCHAINID. */ function safeCHAINID() internal returns ( uint256 _CHAINID ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmCALLER call. * @return _CALLER Result of calling ovmCALLER. */ function safeCALLER() internal returns ( address _CALLER ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCALLER()" ) ); return abi.decode(returndata, (address)); } /** * Performs a safe ovmADDRESS call. * @return _ADDRESS Result of calling ovmADDRESS. */ function safeADDRESS() internal returns ( address _ADDRESS ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Performs a safe ovmGETNONCE call. * @return _nonce Result of calling ovmGETNONCE. */ function safeGETNONCE() internal returns ( uint256 _nonce ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function safeINCREMENTNONCE() internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function safeCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Performs a safe REVERT. * @param _reason String revert reason to pass along with the REVERT. */ function safeREVERT( string memory _reason ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmREVERT(bytes)", Lib_ErrorUtils.encodeRevertString( _reason ) ) ); } /** * Performs a safe "require". * @param _condition Boolean condition that must be true or will revert. * @param _reason String revert reason to pass along with the REVERT. */ function safeREQUIRE( bool _condition, string memory _reason ) internal { if (!_condition) { safeREVERT( _reason ); } } /** * Performs a safe ovmSLOAD call. */ function safeSLOAD( bytes32 _key ) internal returns ( bytes32 ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmSLOAD(bytes32)", _key ) ); return abi.decode(returndata, (bytes32)); } /** * Performs a safe ovmSSTORE call. */ function safeSSTORE( bytes32 _key, bytes32 _value ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmSSTORE(bytes32,bytes32)", _key, _value ) ); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _gasLimit Gas limit for the interaction. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return _returndata Data sent back by the OVM_ExecutionManager. */ function _safeExecutionManagerInteraction( uint256 _gasLimit, bytes memory _calldata ) private returns ( bytes memory _returndata ) { address ovmExecutionManager = msg.sender; ( bool success, bytes memory returndata ) = ovmExecutionManager.call{gas: _gasLimit}(_calldata); if (success == false) { assembly { revert(add(returndata, 0x20), mload(returndata)) } } else if (returndata.length == 1) { assembly { return(0, 1) } } else { return returndata; } } function _safeExecutionManagerInteraction( bytes memory _calldata ) private returns ( bytes memory _returndata ) { return _safeExecutionManagerInteraction( gasleft(), _calldata ); } } // SPDX-License-Identifier: MIT // Pulled from @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_SafeExecutionManagerWrapper } from "./Lib_SafeExecutionManagerWrapper.sol"; /** * @title Lib_SafeMathWrapper */ /** * @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 Lib_SafeMathWrapper { /** * @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 returns (uint256) { uint256 c = a + b; Lib_SafeExecutionManagerWrapper.safeREQUIRE(c >= a, "Lib_SafeMathWrapper: 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 returns (uint256) { return sub(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(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 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; Lib_SafeExecutionManagerWrapper.safeREQUIRE(c / a == b, "Lib_SafeMathWrapper: 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 returns (uint256) { return div(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(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 returns (uint256) { return mod(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(b != 0, errorMessage); return a % b; } }
Computes the address that would be generated by CREATE2. _creator Address creating the contract. _bytecode Bytecode of the contract to be created. _salt 32 byte salt value mixed into the hash. return _address Address to be generated by CREATE2./
function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) internal pure returns (address _address) { bytes32 hashedData = keccak256(abi.encodePacked( byte(0xff), _creator, _salt, keccak256(_bytecode) )); return Lib_Bytes32Utils.toAddress(hashedData); }
10,429,837
pragma solidity ^0.4.18; // File: contracts/zeppelin-solidity-1.4/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/BRDCrowdsaleAuthorizer.sol /** * Contract BRDCrowdsaleAuthorizer is used by the crowdsale website * to autorize wallets to participate in the crowdsale. Because all * participants must go through the KYC/AML phase, only accounts * listed in this contract may contribute to the crowdsale */ contract BRDCrowdsaleAuthorizer is Ownable { // these accounts are authorized to participate in the crowdsale mapping (address => bool) internal authorizedAccounts; // these accounts are authorized to authorize accounts mapping (address => bool) internal authorizers; // emitted when a new account is authorized event Authorized(address indexed _to); // add an authorizer to the authorizers mapping. the _newAuthorizer will // be able to add other authorizers and authorize crowdsale participants function addAuthorizer(address _newAuthorizer) onlyOwnerOrAuthorizer public { // allow the provided address to authorize accounts authorizers[_newAuthorizer] = true; } // remove an authorizer from the authorizers mapping. the _bannedAuthorizer will // no longer have permission to do anything on this contract function removeAuthorizer(address _bannedAuthorizer) onlyOwnerOrAuthorizer public { // only attempt to remove the authorizer if they are currently authorized require(authorizers[_bannedAuthorizer]); // remove the authorizer delete authorizers[_bannedAuthorizer]; } // allow an account to participate in the crowdsale function authorizeAccount(address _newAccount) onlyOwnerOrAuthorizer public { if (!authorizedAccounts[_newAccount]) { // allow the provided account to participate in the crowdsale authorizedAccounts[_newAccount] = true; // emit the Authorized event Authorized(_newAccount); } } // returns whether or not the provided _account is an authorizer function isAuthorizer(address _account) constant public returns (bool _isAuthorizer) { return msg.sender == owner || authorizers[_account] == true; } // returns whether or not the provided _account is authorized to participate in the crowdsale function isAuthorized(address _account) constant public returns (bool _authorized) { return authorizedAccounts[_account] == true; } // allow only the contract creator or one of the authorizers to do this modifier onlyOwnerOrAuthorizer() { require(msg.sender == owner || authorizers[msg.sender]); _; } } // File: contracts/zeppelin-solidity-1.4/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/BRDLockup.sol /** * Contract BRDLockup keeps track of a vesting schedule for pre-sold tokens. * Pre-sold tokens are rewarded up to `numIntervals` times separated by an * `interval` of time. An equal amount of tokens (`allocation` divided by `numIntervals`) * is marked for reward each `interval`. * * The owner of the contract will call processInterval() which will * update the allocation state. The owner of the contract should then * read the allocation data and reward the beneficiaries. */ contract BRDLockup is Ownable { using SafeMath for uint256; // Allocation stores info about how many tokens to reward a beneficiary account struct Allocation { address beneficiary; // account to receive rewards uint256 allocation; // total allocated tokens uint256 remainingBalance; // remaining balance after the current interval uint256 currentInterval; // the current interval for the given reward uint256 currentReward; // amount to be rewarded during the current interval } // the allocation state Allocation[] public allocations; // the date at which allocations begin unlocking uint256 public unlockDate; // the current unlock interval uint256 public currentInterval; // the interval at which allocations will be rewarded uint256 public intervalDuration; // the number of total reward intervals, zero indexed uint256 public numIntervals; event Lock(address indexed _to, uint256 _amount); event Unlock(address indexed _to, uint256 _amount); // constructor // @param _crowdsaleEndDate - the date the crowdsale ends function BRDLockup(uint256 _crowdsaleEndDate, uint256 _numIntervals, uint256 _intervalDuration) public { unlockDate = _crowdsaleEndDate; numIntervals = _numIntervals; intervalDuration = _intervalDuration; currentInterval = 0; } // update the allocation storage remaining balances function processInterval() onlyOwner public returns (bool _shouldProcessRewards) { // ensure the time interval is correct bool _correctInterval = now >= unlockDate && now.sub(unlockDate) > currentInterval.mul(intervalDuration); bool _validInterval = currentInterval < numIntervals; if (!_correctInterval || !_validInterval) return false; // advance the current interval currentInterval = currentInterval.add(1); // number of iterations to read all allocations uint _allocationsIndex = allocations.length; // loop through every allocation for (uint _i = 0; _i < _allocationsIndex; _i++) { // the current reward for the allocation at index `i` uint256 _amountToReward; // if we are at the last interval, the reward amount is the entire remaining balance if (currentInterval == numIntervals) { _amountToReward = allocations[_i].remainingBalance; } else { // otherwise the reward amount is the total allocation divided by the number of intervals _amountToReward = allocations[_i].allocation.div(numIntervals); } // update the allocation storage allocations[_i].currentReward = _amountToReward; } return true; } // the total number of allocations function numAllocations() constant public returns (uint) { return allocations.length; } // the amount allocated for beneficiary at `_index` function allocationAmount(uint _index) constant public returns (uint256) { return allocations[_index].allocation; } // reward the beneficiary at `_index` function unlock(uint _index) onlyOwner public returns (bool _shouldReward, address _beneficiary, uint256 _rewardAmount) { // ensure the beneficiary is not rewarded twice during the same interval if (allocations[_index].currentInterval < currentInterval) { // record the currentInterval so the above check is useful allocations[_index].currentInterval = currentInterval; // subtract the reward from their remaining balance allocations[_index].remainingBalance = allocations[_index].remainingBalance.sub(allocations[_index].currentReward); // emit event Unlock(allocations[_index].beneficiary, allocations[_index].currentReward); // return value _shouldReward = true; } else { // return value _shouldReward = false; } // return values _rewardAmount = allocations[_index].currentReward; _beneficiary = allocations[_index].beneficiary; } // add a new allocation to the lockup function pushAllocation(address _beneficiary, uint256 _numTokens) onlyOwner public { require(now < unlockDate); allocations.push( Allocation( _beneficiary, _numTokens, _numTokens, 0, 0 ) ); Lock(_beneficiary, _numTokens); } } // File: contracts/zeppelin-solidity-1.4/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/zeppelin-solidity-1.4/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/zeppelin-solidity-1.4/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/zeppelin-solidity-1.4/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/zeppelin-solidity-1.4/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: contracts/BRDToken.sol contract BRDToken is MintableToken { using SafeMath for uint256; string public name = "Bread Token"; string public symbol = "BRD"; uint256 public decimals = 18; // override StandardToken#transferFrom // ensures that minting has finished or the message sender is the token owner function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(mintingFinished || msg.sender == owner); return super.transferFrom(_from, _to, _value); } // override StandardToken#transfer // ensures the minting has finished or the message sender is the token owner function transfer(address _to, uint256 _value) public returns (bool) { require(mintingFinished || msg.sender == owner); return super.transfer(_to, _value); } } // File: contracts/zeppelin-solidity-1.4/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } // File: contracts/zeppelin-solidity-1.4/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: contracts/BRDCrowdsale.sol contract BRDCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // maximum amount of wei raised during this crowdsale uint256 public cap; // minimum per-participant wei contribution uint256 public minContribution; // maximum per-participant wei contribution uint256 public maxContribution; // how many token unites the owner gets per buyer wei uint256 public ownerRate; // number of tokens per 100 to lock up in lockupTokens() uint256 public bonusRate; // crowdsale authorizer contract determines who can participate BRDCrowdsaleAuthorizer public authorizer; // the lockup contract holds presale authorization amounts BRDLockup public lockup; // constructor function BRDCrowdsale( uint256 _cap, // maximum wei raised uint256 _minWei, // minimum per-contributor wei uint256 _maxWei, // maximum per-contributor wei uint256 _startTime, // crowdsale start time uint256 _endTime, // crowdsale end time uint256 _rate, // tokens per wei uint256 _ownerRate, // owner tokens per buyer wei uint256 _bonusRate, // percentage of tokens to lockup address _wallet) // target funds wallet Crowdsale(_startTime, _endTime, _rate, _wallet) public { require(_cap > 0); cap = _cap; minContribution = _minWei; maxContribution = _maxWei; ownerRate = _ownerRate; bonusRate = _bonusRate; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool _capReached = weiRaised >= cap; return super.hasEnded() || _capReached; } // @return true if the crowdsale has started function hasStarted() public constant returns (bool) { return now > startTime; } // overriding Crowdsale#buyTokens // mints the ownerRate of tokens in addition to calling the super method function buyTokens(address _beneficiary) public payable { // call the parent method to mint tokens to the beneficiary super.buyTokens(_beneficiary); // calculate the owner share of tokens uint256 _ownerTokens = msg.value.mul(ownerRate); // mint the owner share and send to the owner wallet token.mint(wallet, _ownerTokens); } // mints _amount tokens to the _beneficiary minus the bonusRate // tokens to be locked up via the lockup contract. locked up tokens // are sent to the contract and may be unlocked according to // the lockup configuration after the sale ends function lockupTokens(address _beneficiary, uint256 _amount) onlyOwner public { require(!isFinalized); // calculate the owner share of tokens uint256 _ownerTokens = ownerRate.mul(_amount).div(rate); // mint the owner share and send to the owner wallet token.mint(wallet, _ownerTokens); // calculate the amount of tokens to be locked up uint256 _lockupTokens = bonusRate.mul(_amount).div(100); // create the locked allocation in the lockup contract lockup.pushAllocation(_beneficiary, _lockupTokens); // mint locked tokens to the crowdsale contract to later be unlocked token.mint(this, _lockupTokens); // the non-bonus tokens are immediately rewarded uint256 _remainder = _amount.sub(_lockupTokens); token.mint(_beneficiary, _remainder); } // unlocks tokens from the token lockup contract. no tokens are held by // the lockup contract, just the amounts and times that tokens should be rewarded. // the tokens are held by the crowdsale contract function unlockTokens() onlyOwner public returns (bool _didIssueRewards) { // attempt to process the interval. it update the allocation bookkeeping // and will only return true when the interval should be processed if (!lockup.processInterval()) return false; // the total number of allocations uint _numAllocations = lockup.numAllocations(); // for every allocation, attempt to unlock the reward for (uint _i = 0; _i < _numAllocations; _i++) { // attempt to unlock the reward var (_shouldReward, _to, _amount) = lockup.unlock(_i); // if the beneficiary should be rewarded, send them tokens if (_shouldReward) { token.transfer(_to, _amount); } } return true; } // sets the authorizer contract if the crowdsale hasn't started function setAuthorizer(BRDCrowdsaleAuthorizer _authorizer) onlyOwner public { require(!hasStarted()); authorizer = _authorizer; } // sets the lockup contract if the crowdsale hasn't started function setLockup(BRDLockup _lockup) onlyOwner public { require(!hasStarted()); lockup = _lockup; } // sets the token contract if the crowdsale hasn't started function setToken(BRDToken _token) onlyOwner public { require(!hasStarted()); token = _token; } // allows maxContribution to be modified function setMaxContribution(uint256 _newMaxContribution) onlyOwner public { maxContribution = _newMaxContribution; } // allows endTime to be modified function setEndTime(uint256 _newEndTime) onlyOwner public { endTime = _newEndTime; } // overriding Crowdsale#createTokenContract function createTokenContract() internal returns (MintableToken) { // set the token to null initially // call setToken() above to set the actual token address return BRDToken(address(0)); } // overriding FinalizableCrowdsale#finalization // finalizes minting for the token contract, disabling further minting function finalization() internal { // end minting token.finishMinting(); // issue the first lockup reward unlockTokens(); super.finalization(); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if crowdsale participants can buy at the moment // checks whether the cap has not been reached, the purchaser has // been authorized, and their contribution is within the min/max // thresholds function validPurchase() internal constant returns (bool) { bool _withinCap = weiRaised.add(msg.value) <= cap; bool _isAuthorized = authorizer.isAuthorized(msg.sender); bool _isMin = msg.value >= minContribution; uint256 _alreadyContributed = token.balanceOf(msg.sender).div(rate); bool _withinMax = msg.value.add(_alreadyContributed) <= maxContribution; return super.validPurchase() && _withinCap && _isAuthorized && _isMin && _withinMax; } }
update the allocation storage remaining balances ensure the time interval is correct advance the current interval number of iterations to read all allocations loop through every allocation the current reward for the allocation at index `i` if we are at the last interval, the reward amount is the entire remaining balance otherwise the reward amount is the total allocation divided by the number of intervals
function processInterval() onlyOwner public returns (bool _shouldProcessRewards) { bool _correctInterval = now >= unlockDate && now.sub(unlockDate) > currentInterval.mul(intervalDuration); bool _validInterval = currentInterval < numIntervals; if (!_correctInterval || !_validInterval) return false; currentInterval = currentInterval.add(1); uint _allocationsIndex = allocations.length; for (uint _i = 0; _i < _allocationsIndex; _i++) { uint256 _amountToReward; if (currentInterval == numIntervals) { _amountToReward = allocations[_i].remainingBalance; _amountToReward = allocations[_i].allocation.div(numIntervals); } } return true; }
12,589,018
./partial_match/56/0x4FE4b0FA3D082CDD9f7f630D6aB271a23bCDb4C4/sources/Vault.sol
function deposit(uint256 amountToken) external payable;
interface IVault { function totalToken() external view returns (uint256); function withdraw(uint256 share) external; function requestFunds(address targetedToken, uint amount) external; } }
11,192,204
./full_match/4/0xcd4420F4A3E7EF2b4bD1a39004379e9D218378D5/sources/vestingBondDepository.sol
/ slippage protection Deposit token to mint OHM Store depositor info/ store updated deposit info
@notice deposit function like mint @param amount_ uint @param maxPrice_ uint @param depositor_ address @return bool function _deposit( uint amount_, uint maxPrice_, address depositor_, address token_ ) internal returns ( bool ) { if ( token_ == DAI ) { value = amount_.div( 1e9 ); term = vestingTermForDAI; price = _calcPriceForDAI(); value = IBondCalculator( bondCalculator ).valuation( token_ , amount_ ); term = vestingTermForLP; price = _calcPriceForLP(); uint priceInDAI = _calcPriceForDAI(); require( maxPrice_ >= priceInDAI, "More than max premium" ); IERC20( token_ ).safeTransferFrom( msg.sender, address(this), amount_ ); uint payout = calculateBondInterest( value, price ); require( payout <= getMaxPayoutAmount(), "Payout too large"); totalDebt = totalDebt.add( payout ); IERC20( token_ ).approve( address( treasury ), amount_ ); if ( token_ == DAI ) { ITreasury( treasury ).depositReserves( amount_, DAI ); ITreasury( treasury ).depositPrinciple( amount_, LP ); } uint daoProfit = payout.mul( DAOShare ).div( 10000 ); uint profit = value.sub( payout ).sub( daoProfit ); IERC20( OHM ).safeTransfer( DAOWallet, daoProfit ); depositorInfo[ depositor_ ][ lastIndex[ depositor_ ] ] = DepositInfo({ payoutRemaining: payout, lastBlock: block.number, vestingPeriod: term, pricePaid: priceInDAI, vested: false }); lastIndex[ depositor_ ]++; return true; } @return bool function redeem() external returns ( bool ) { for ( uint i = firstIndex[ msg.sender ]; i < lastIndex[ msg.sender ]; i++ ) { DepositInfo memory info = depositorInfo[ msg.sender ][ i ]; if ( !info.vested ) { uint percentVested = _calculatePercentVested( msg.sender, i ); IERC20( OHM ).transfer( msg.sender, info.payoutRemaining ); totalDebt = totalDebt.sub( info.payoutRemaining ); depositorInfo[msg.sender][ i ] = DepositInfo({ payoutRemaining: 0, lastBlock: block.number, vestingPeriod: 0, pricePaid: info.pricePaid, vested: true }); IERC20( OHM ).transfer( msg.sender, payout ); uint blocksSinceLast = block.number.sub( info.lastBlock ); depositorInfo[msg.sender][ i ] = DepositInfo({ payoutRemaining: info.payoutRemaining.sub( payout ), lastBlock: block.number, vestingPeriod: info.vestingPeriod.sub( blocksSinceLast ), pricePaid: info.pricePaid, vested: false }); } } if ( info.vested && i == firstIndex[ msg.sender ] ) { firstIndex[ msg.sender ] = i++; } } return true; } @param address_ info
747,901
pragma solidity ^0.5.0; contract TestContract { function swapAllAndMix23(uint a, uint b, uint c) public returns (uint, uint, uint) { uint mixed = mixParameters(b, c); uint a1; uint b1; // Weed out solutions with less than 2-context-sensitivity swapParameters(a, b); swapParameters(b, c); swapParameters(a, c); mixParameters(a, c); mixParameters(a, b); (b1, a1) = swapParameters(mixed, a); return (c, a1, b1); } function swapAllAndMix23_1(uint a, uint b, uint c) public returns (uint, uint, uint) { uint mixed = mixParameters(b, c); uint a1; uint b1; // Weed out solutions with less than 2-context-sensitivity swapParameters(a, b); swapParameters(b, c); swapParameters(a, c); mixParameters(a, c); mixParameters(a, b); (b1, a1) = swapParameters(mixed, a); return (c, a1, b1); } function swapAllAndMix23_2(uint a, uint b, uint c) public returns (uint, uint, uint) { uint mixed = mixParameters(b, c); uint a1; uint b1; // Weed out solutions with less than 2-context-sensitivity swapParameters(a, b); swapParameters(b, c); swapParameters(a, c); mixParameters(a, c); mixParameters(a, b); (b1, a1) = swapParameters(mixed, a); return (c, a1, b1); } function swapAllAndMix23_3(uint a, uint b, uint c) public returns (uint, uint, uint) { uint mixed = mixParameters(b, c); uint a1; uint b1; // Weed out solutions with less than 2-context-sensitivity swapParameters(a, b); swapParameters(b, c); swapParameters(a, c); mixParameters(a, c); mixParameters(a, b); (b1, a1) = swapParameters(mixed, a); return (c, a1, b1); } function mixParameters(uint a, uint b) public returns (uint) { return a * b; } function swapParameters(uint a, uint b) public returns (uint, uint) { uint a1; uint b1; a1 = b + 5; // Add some "noise instructions" b1 = a + 5; return (a1 - 5, b1 - 5); } function mixParameters_1(uint a, uint b) public returns (uint) { return a * b; } function swapParameters_1(uint a, uint b) public returns (uint, uint) { uint a1; uint b1; a1 = b + 5; // Add some "noise instructions" b1 = a + 5; return (a1 - 5, b1 - 5); } function mixParameters_2(uint a, uint b) public returns (uint) { return a * b; } function swapParameters_2(uint a, uint b) public returns (uint, uint) { uint a1; uint b1; a1 = b + 5; // Add some "noise instructions" b1 = a + 5; return (a1 - 5, b1 - 5); } function mixParameters_3(uint a, uint b) public returns (uint) { return a * b; } function swapParameters_3(uint a, uint b) public returns (uint, uint) { uint a1; uint b1; a1 = b + 5; // Add some "noise instructions" b1 = a + 5; return (a1 - 5, b1 - 5); } function mixParameters_4(uint a, uint b) public returns (uint) { return a * b; } function swapParameters_4(uint a, uint b) public returns (uint, uint) { uint a1; uint b1; a1 = b + 5; // Add some "noise instructions" b1 = a + 5; return (a1 - 5, b1 - 5); } function main() public payable { swapAllAndMix23(msg.value, msg.value, msg.value); (uint a, uint b, uint c) = swapAllAndMix23(4, msg.value, 5); sink(a); sink(c); } function main_1() public payable { swapAllAndMix23(msg.value, msg.value, msg.value); (uint a, uint b, uint c) = swapAllAndMix23(4, msg.value, 5); sink(a); sink(c); } function main_2() public payable { swapAllAndMix23(msg.value, msg.value, msg.value); (uint a, uint b, uint c) = swapAllAndMix23(4, msg.value, 5); sink(a); sink(c); } // Sink functions (need to be part of the contract) function sink(address _) pure public {} function sink(uint _) pure public {} }
Weed out solutions with less than 2-context-sensitivity
function swapAllAndMix23_3(uint a, uint b, uint c) public returns (uint, uint, uint) { uint mixed = mixParameters(b, c); uint a1; uint b1; swapParameters(a, b); swapParameters(b, c); swapParameters(a, c); mixParameters(a, c); mixParameters(a, b); (b1, a1) = swapParameters(mixed, a); return (c, a1, b1); }
14,108,805
./full_match/80001/0xdaA8D468235317a5776CEf9BC15E83625ca34C08/sources/project_/contracts/SportsBetting.sol
this is not for entering a bet and will only add money to the total pool
function bonus() external payable { totalPool += msg.value; }
836,502
./full_match/1/0x84fE05f541cee93d0B02e03cD4319c29BA0030A2/sources/src/osp/OneStepProverMemory.sol
Apply the last leaf update
function executeMemoryStore( Machine memory mach, Module memory mod, Instruction calldata inst, bytes calldata proof ) internal pure { uint64 writeBytes; uint64 toWrite; { ValueType ty; if (inst.opcode == Instructions.I32_STORE) { ty = ValueType.I32; writeBytes = 4; ty = ValueType.I64; writeBytes = 8; ty = ValueType.F32; writeBytes = 4; ty = ValueType.F64; writeBytes = 8; ty = ValueType.I32; writeBytes = 1; ty = ValueType.I32; writeBytes = 2; ty = ValueType.I64; writeBytes = 1; ty = ValueType.I64; writeBytes = 2; ty = ValueType.I64; writeBytes = 4; revert("INVALID_MEMORY_STORE_OPCODE"); } Value memory writingVal = mach.valueStack.pop(); require(writingVal.valueType == ty, "BAD_STORE_TYPE"); toWrite = uint64(writingVal.contents); if (writeBytes < 8) { toWrite &= (uint64(1) << (writeBytes * 8)) - 1; } } if (startIdx + writeBytes > mod.moduleMemory.size) { mach.status = MachineStatus.ERRORED; return; } uint256 proofOffset = 0; uint256 lastProvedLeafIdx = ~uint256(0); MerkleProof memory lastProvedMerkle; bytes32 lastProvedLeafContents; for (uint256 i = 0; i < writeBytes; i++) { uint256 idx = startIdx + i; uint256 leafIdx = idx / LEAF_SIZE; if (leafIdx != lastProvedLeafIdx) { if (lastProvedLeafIdx != ~uint256(0)) { mod.moduleMemory.merkleRoot = lastProvedMerkle.computeRootFromMemory( lastProvedLeafIdx, lastProvedLeafContents ); } mod.moduleMemory, leafIdx, proof, proofOffset ); lastProvedLeafIdx = leafIdx; } uint256 indexWithinLeaf = idx % LEAF_SIZE; lastProvedLeafContents = setLeafByte( lastProvedLeafContents, indexWithinLeaf, uint8(toWrite) ); toWrite >>= 8; } mod.moduleMemory.merkleRoot = lastProvedMerkle.computeRootFromMemory( lastProvedLeafIdx, lastProvedLeafContents ); }
3,877,567
./partial_match/1/0xCC2e29c905f77dadde0086f8fcF12C68F0b368d1/sources/ForeignBridgeNativeToErc.sol
Total number of tokens in existence/
function messageWithinLimits(uint256) internal view returns(bool); function onFailedMessage(address, uint256, bytes32) internal; } pragma solidity ^0.4.24; function totalSupply() public view returns (uint256) { return _totalSupply; }
16,200,612
./partial_match/1/0x56146633c6C9D3536eEBbf0bcB1D5F20A788B82a/sources/ETHRegistrarController.sol
Require a valid commitment (is old enough and is committed) If the commitment is too old, or the name is registered, stop
function _consumeCommitment( string memory name, string memory tld, uint256 duration, bytes32 commitment ) internal { require( commitments[commitment] + minCommitmentAge <= block.timestamp, "ETHRegistrarController: Commitment is not valid" ); require( commitments[commitment] + maxCommitmentAge > block.timestamp, "ETHRegistrarController: Commitment has expired" ); require(available(name, tld), "ETHRegistrarController: Name is unavailable"); delete (commitments[commitment]); require(duration >= MIN_REGISTRATION_DURATION, "ETHRegistrarController: Duration too low"); }
4,198,053
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); } 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); } contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract ParentToken { /* library used for calculations */ using SafeMath for uint256; /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address=>uint)) allowance; /* Initializes contract with initial supply tokens to the creator of the contract */ function ParentToken(uint256 currentSupply, string tokenName, uint8 decimalUnits, string tokenSymbol){ balances[msg.sender] = currentSupply; // Give the creator all initial tokens totalSupply = currentSupply; // Update total supply name = tokenName; // Set the name for display purposes decimals = decimalUnits; // Decimals for the tokens symbol = tokenSymbol; // Set the symbol for display purposes } ///@notice Transfer tokens to the beneficiary account ///@param to The beneficiary account ///@param value The amount of tokens to be transfered function transfer(address to, uint value) returns (bool success){ require( balances[msg.sender] >= value && value > 0 ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); return true; } ///@notice Allow another contract to spend some tokens in your behalf ///@param spender The address authorized to spend ///@param value The amount to be approved function approve(address spender, uint256 value) returns (bool success) { allowance[msg.sender][spender] = value; return true; } ///@notice Approve and then communicate the approved contract in a single tx ///@param spender The address authorized to spend ///@param value The amount to be approved function approveAndCall(address spender, uint256 value, bytes extraData) returns (bool success) { tokenRecipient recSpender = tokenRecipient(spender); if (approve(spender, value)) { recSpender.receiveApproval(msg.sender, value, this, extraData); return true; } } ///@notice Transfer tokens between accounts ///@param from The benefactor/sender account. ///@param to The beneficiary account ///@param value The amount to be transfered function transferFrom(address from, address to, uint value) returns (bool success){ require( allowance[from][msg.sender] >= value &&balances[from] >= value && value > 0 ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); return true; } } library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { assert(b > 0); 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; } } } contract MLC is owned,ParentToken{ /* library used for calculations */ using SafeMath for uint256; /* Public variables of the token */ string public standard = 'Token 0.1'; uint256 public currentSupply= 2400000000000000; string public constant symbol = "MLC"; string public constant tokenName = "Melania"; uint8 public constant decimals = 8; mapping (address => bool) public frozenAccount; ///@notice Default function used for any payments made. function () payable { acceptPayment(); } ///@notice Accept payment and transfer to owner account. function acceptPayment() payable { require(msg.value>0); owner.transfer(msg.value); } function MLC()ParentToken(currentSupply,tokenName,decimals,symbol){} ///@notice Provides balance of the account requested ///@param add Address of the account for which balance is being enquired function balanceOf(address add) constant returns (uint balance){ return balances[add]; } ///@notice Transfer tokens to the beneficiary account ///@param to The beneficiary account ///@param value The amount of tokens to be transfered function transfer(address to, uint value) returns (bool success){ require( balances[msg.sender] >= value && value > 0 && (!frozenAccount[msg.sender]) // Allow transfer only if account is not frozen ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); // Update the balance of beneficiary account Transfer(msg.sender,to,value); return true; } ///@notice Transfer tokens between accounts ///@param from The benefactor/sender account. ///@param to The beneficiary account ///@param value The amount to be transfered function transferFrom(address from, address to, uint value) returns (bool success){ require( allowance[from][msg.sender] >= value &&balances[from] >= value //Check if the benefactor has sufficient balance && value > 0 && (!frozenAccount[msg.sender]) // Allow transfer only if account is not frozen ); balances[from] = balances[from].sub(value); // Deduct from the benefactor account balances[to] = balances[to].add(value); // Update the balance of beneficiary account allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); Transfer(from,to,value); return true; } ///@notice Increase the number of coins ///@param target The address of the account where the coins would be added. ///@param mintedAmount The amount of coins to be added function mintToken(address target, uint256 mintedAmount) onlyOwner { balances[target] = balances[target].add(mintedAmount); //Add the amount of coins to be increased to the balance currentSupply = currentSupply.add(mintedAmount); //Add the amount of coins to be increased to the supply Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } ///@notice Freeze the account at the target address ///@param target The address of the account to be frozen function freezeAccount(address target, bool freeze) onlyOwner { require(freeze); //Check if account has to be freezed frozenAccount[target] = freeze; //Freeze the account FrozenFunds(target, freeze); } /// @notice Remove tokens from the system irreversibly /// @param value The amount of money to burn function burn(uint256 value) returns (bool success) { require (balances[msg.sender] > value && value>0); // Check if the sender has enough balance balances[msg.sender] = balances[msg.sender].sub(value); // Deduct from the sender currentSupply = currentSupply.sub(value); // Update currentSupply Burn(msg.sender, value); return true; } function burnFrom(address from, uint256 value) returns (bool success) { require(balances[from] >= value); // Check if the targeted balance is enough require(value <= allowance[from][msg.sender]); // Check allowance balances[from] = balances[from].sub(value); // Deduct from the targeted balance allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); // Deduct from the sender's allowance currentSupply = currentSupply.sub(value); // Update currentSupply Burn(from, value); return true; } /* This notifies clients about the amount transfered */ event Transfer(address indexed _from, address indexed _to,uint256 _value); /* This notifies clients about the amount approved */ event Approval(address indexed _owner, address indexed _spender,uint256 _value); /* This notifies clients about the account freeze */ event FrozenFunds(address target, bool frozen); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); }
Remove tokens from the system irreversibly value The amount of money to burn
function burn(uint256 value) returns (bool success) { Burn(msg.sender, value); return true; }
4,805,701
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; interface ILayerZeroUserApplicationConfig { // @notice set the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _configType - type of configuration. every messaging library has its own convention. // @param _config - configuration in the bytes. can encode arbitrary content. function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external; // @notice set the send() LayerZero messaging library version to _version // @param _version - new messaging library version function setSendVersion(uint16 _version) external; // @notice set the lzReceive() LayerZero messaging library version to _version // @param _version - new messaging library version function setReceiveVersion(uint16 _version) external; // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload // @param _srcChainId - the chainId of the source chain // @param _srcAddress - the contract address of the source contract at the source chain function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; } pragma solidity ^0.8.7; interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig { // @notice send a LayerZero message to the specified address at a LayerZero endpoint. // @param _dstChainId - the destination chain identifier // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains // @param _payload - a custom bytes payload to send to the destination contract // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable; // @notice used by the messaging library to publish verified payload // @param _srcChainId - the source chain identifier // @param _srcAddress - the source contract (as bytes) at the source chain // @param _dstAddress - the address on destination chain // @param _nonce - the unbound message ordering nonce // @param _gasLimit - the gas limit for external contract execution // @param _payload - verified payload to send to the destination contract function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external; // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64); // @notice get the outboundNonce from this source chain which, consequently, is always an EVM // @param _srcAddress - the source chain contract address function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64); // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery // @param _dstChainId - the destination chain identifier // @param _userApplication - the user app address on this EVM chain // @param _payload - the custom message to send over LayerZero // @param _payInZRO - if false, user app pays the protocol fee in native token // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee); // @notice get this Endpoint's immutable source identifier function getChainId() external view returns (uint16); // @notice the interface to retry failed message on this Endpoint destination // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address // @param _payload - the payload to be retried function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external; // @notice query if any STORED payload (message blocking) at the endpoint. // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool); // @notice query if the _libraryAddress is valid for sending msgs. // @param _userApplication - the user app address on this EVM chain function getSendLibraryAddress(address _userApplication) external view returns (address); // @notice query if the _libraryAddress is valid for receiving msgs. // @param _userApplication - the user app address on this EVM chain function getReceiveLibraryAddress(address _userApplication) external view returns (address); // @notice query if the non-reentrancy guard for send() is on // @return true if the guard is on. false otherwise function isSendingPayload() external view returns (bool); // @notice query if the non-reentrancy guard for receive() is on // @return true if the guard is on. false otherwise function isReceivingPayload() external view returns (bool); // @notice get the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _userApplication - the contract address of the user application // @param _configType - type of configuration. every messaging library has its own convention. function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory); // @notice get the send() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getSendVersion(address _userApplication) external view returns (uint16); // @notice get the lzReceive() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getReceiveVersion(address _userApplication) external view returns (uint16); } pragma solidity ^0.8.7; interface ILayerZeroReceiver { // @notice LayerZero endpoint will invoke this function to deliver the message on the destination // @param _srcChainId - the source endpoint identifier // @param _srcAddress - the source sending contract address from the source chain // @param _nonce - the ordered message nonce // @param _payload - the signed payload is the UA bytes has encoded to be sent function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external; } pragma solidity ^0.8.7; /** * @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); } } pragma solidity ^0.8.7; /** * @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; } } pragma solidity ^0.8.7; /** * @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); } } pragma solidity ^0.8.7; /** * @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); } } } } pragma solidity ^0.8.7; /** * @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); } pragma solidity ^0.8.7; /** * @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); } pragma solidity ^0.8.7; /** * @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; } } pragma solidity ^0.8.7; /** * @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; } pragma solidity ^0.8.7; /** * @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); } pragma solidity ^0.8.7; /** * @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); } pragma solidity ^0.8.7; abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver { ILayerZeroEndpoint internal endpoint; struct FailedMessages { uint payloadLength; bytes32 payloadHash; } mapping(uint16 => mapping(bytes => mapping(uint => FailedMessages))) public failedMessages; mapping(uint16 => bytes) public trustedRemoteLookup; event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload); function lzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) external override { require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security require(_srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]), "NonblockingReceiver: invalid source sending contract"); // try-catch all errors/exceptions // having failed messages does not block messages passing try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) { // do nothing } catch { // error / exception failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(_payload.length, keccak256(_payload)); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload); } } function onLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public { // only internal transaction require(msg.sender == address(this), "NonblockingReceiver: caller must be Bridge."); // handle incoming message _LzReceive( _srcChainId, _srcAddress, _nonce, _payload); } // abstract function function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) virtual internal; function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam) internal { endpoint.send{value: msg.value}(_dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam); } function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable { // assert there is message to retry FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce]; require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message"); require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload"); // clear the stored message failedMsg.payloadLength = 0; failedMsg.payloadHash = bytes32(0); // execute the message. revert if it fails again this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner { trustedRemoteLookup[_chainId] = _trustedRemote; } } pragma solidity ^0.8.7; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721B is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 private TotalToken = 0; uint256 private MaxTokenId = 0; uint256 internal immutable maxBatchSize; uint256 private startIndex = 0; uint256 private endIndex = 0; address private burnaddress = 0x000000000000000000000000000000000000dEaD; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `TotalToken_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 startIndex_, uint256 endIndex_ ) { require(maxBatchSize_ > 0, "ERC721B: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; currentIndex = startIndex_; startIndex = startIndex_; endIndex = endIndex_; MaxTokenId = endIndex_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return TotalToken; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index <= MaxTokenId, "ERC721B: global index out of bounds"); uint256 tokenIdsIdx = 0; for (uint256 i = 0; i <= MaxTokenId; i++) { TokenOwnership memory ownership = _ownerships[i]; if(_inrange(i)){ if ( (ownership.addr != burnaddress) && (i < currentIndex)) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } else { if ((ownership.addr != address(0)) && (ownership.addr != burnaddress)) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert("ERC721A: unable to get token by index"); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(TotalToken). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i <= MaxTokenId; i++) { TokenOwnership memory ownership = _ownerships[i]; if(_inrange(i) && (i < currentIndex)){ if ((ownership.addr != address(0))) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } else { if (ownership.addr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721B: balance query for the zero address"); require(owner != burnaddress, "ERC721B: balance query for the burnaddress"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); require( owner != burnaddress, "ERC721A: number minted query for the burnaddress" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721B: owner query for nonexistent token"); //If it is airdrop(transfered between chains), we have owner address set already. TokenOwnership memory ownership = _ownerships[tokenId]; if ( !_inrange(tokenId) ) { if ( (ownership.addr != address(0)) && (ownership.addr != burnaddress) ) return ownership; else revert("ERC721B: unable to determine the owner of token"); } uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } if (lowestTokenToCheck < startIndex) { lowestTokenToCheck = startIndex; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { ownership = _ownerships[curr]; if ((ownership.addr != address(0)) && (ownership.addr != burnaddress) ) { return ownership; } } revert("ERC721B: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721B.ownerOf(tokenId); require(to != owner, "ERC721B: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721B: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721B: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721B: 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 { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721B: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { //@dan token could be out of range from tranferring between blockchains if (_inrange(tokenId)) { return ((tokenId < currentIndex) && (_ownerships[tokenId].addr !=burnaddress)); } else { return ((_ownerships[tokenId].addr != address(0)) && (_ownerships[tokenId].addr !=burnaddress)); } } /** * @dev Returns whether `tokenId` in start and end ranges. * * Tokens can be out of range by airdrop. */ function _inrange(uint256 tokenId) internal view returns (bool) { //@dan token could be out of range from tranferring between blockchains return ((tokenId >= startIndex) && (tokenId <= endIndex)); } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721B: mint to the zero address"); require(to != burnaddress, "ERC721B: mint to the burn address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721B: token already minted"); require(quantity <= maxBatchSize, "ERC721B: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; TotalToken++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Safely airdrop `tokenId` and transfers it to `to`. This is for the receive side of Level Zero Chain transfer * * 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 _airdrop(address to, uint256 tokenId) internal virtual { _airdrop(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 _airdrop( address to, uint256 tokenId, bytes memory _data ) internal virtual { _airdropbyId(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 _airdropbyId(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(to != burnaddress, "ERC721B: mint to the burn address"); _beforeTokenTransfers(address(0), to, tokenId, 1); TotalToken++; if(tokenId > MaxTokenId){ MaxTokenId = tokenId; } AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + 1, addressData.numberMinted + 1); _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); emit Transfer(address(0), to, tokenId); } /** * @dev ERC721A uses address(0), so we use 0x000000000000000000000000000000000000dEaD as burn address * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); address owner = ERC721B.ownerOf(tokenId); _beforeTokenTransfers(owner, burnaddress, tokenId, 1); // Clear approvals _approve(address(0), tokenId, owner); AddressData memory addressData = _addressData[owner]; _addressData[owner] = AddressData( addressData.balance - 1, addressData.numberMinted - 1); TotalToken--; _ownerships[tokenId] = TokenOwnership(burnaddress, uint64(block.timestamp)); //@dan only do this if minted in range. // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_inrange(nextTokenId) && (_ownerships[nextTokenId].addr == address(0))) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721B: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721B: transfer from incorrect owner" ); require(to != address(0), "ERC721B: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); //@dan only do this if minted in range. // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_inrange(nextTokenId) && (_ownerships[nextTokenId].addr == address(0))) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721B: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } pragma solidity ^0.8.7; interface IGOKU { function burn(address _from, uint256 _amount) external; } contract GokudoParadiseContract is Ownable, ERC721B, NonblockingReceiver { string private baseURI; uint256 public MAX_MINT_ETHEREUM; uint256 public Mintprice = 29000000000000000; uint256 constant public UPGRADE_PRICE = 5000 ether; uint public MaxPatchPerTx; bool public bSalesStart = false; bool public bUpgradeIsActive = false; uint gasForDestinationLzReceive = 350000; mapping(uint16 => address) private _TopEXAddress; mapping(uint => uint256) public upgradenewtokenid; event InternaltokenidChange(address _by, uint _tokenId, uint256 _internaltokenID); IGOKU public GOKU; constructor( uint256 maxBatchSize_, uint256 startIndex_, uint256 endIndex_, address _layerZeroEndpoint ) ERC721B("Gokudo Paradise", "GokudoParadise", maxBatchSize_, startIndex_, endIndex_) { MaxPatchPerTx = maxBatchSize_; MAX_MINT_ETHEREUM = endIndex_ + 1; endpoint = ILayerZeroEndpoint(_layerZeroEndpoint); // Use top exchange addresses to seed random number. Changes every second _TopEXAddress[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; _TopEXAddress[1] = 0xDA9dfA130Df4dE4673b89022EE50ff26f6EA73Cf; _TopEXAddress[2] = 0x6262998Ced04146fA42253a5C0AF90CA02dfd2A3; _TopEXAddress[3] = 0xA7EFAe728D2936e78BDA97dc267687568dD593f3; _TopEXAddress[4] = 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8; } function setMaxMintNum(uint _MAX_MINT) external onlyOwner { MAX_MINT_ETHEREUM = _MAX_MINT; } function setMintprice(uint _Mintprice) external onlyOwner { Mintprice = _Mintprice; } function flipSalesStart() public onlyOwner { bSalesStart = !bSalesStart; } function flipUpgradeIsActive() public onlyOwner { bUpgradeIsActive = !bUpgradeIsActive; } // mint function function mint(uint8 numTokens) external payable { require(bSalesStart, "Sale is not started"); require(totalSupply() + numTokens <= MAX_MINT_ETHEREUM, "Can not mint more than MAX_MINT_ETHEREUM"); require(numTokens > 0 && numTokens <= MaxPatchPerTx, "Can not mint more than MaxPatchPerTx"); require(msg.value >= Mintprice*numTokens, "Not paid enough ETH."); _safeMint(msg.sender, numTokens); } function MintByOwner(address _to,uint256 mintamount) external onlyOwner { require(totalSupply() + mintamount <= MAX_MINT_ETHEREUM, "Can not mint more than MAX_MINT_ETHEREUM"); _safeMint(_to, mintamount); } // This function transfers the nft from your address on the // source chain to the same address on the destination chain function traverseChains(uint16 _chainId, uint tokenId) public payable { require(msg.sender == ownerOf(tokenId), "You must own the token to traverse"); require(trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel"); // burn NFT, eliminating it from circulation on src chain _burn(tokenId); // abi.encode() the payload with the values to send bytes memory payload = abi.encode(msg.sender, tokenId); // encode adapterParams to specify more gas for the destination uint16 version = 1; bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive); // get the fees we need to pay to LayerZero + Relayer to cover message delivery // you will be refunded for extra gas paid (uint messageFee, ) = endpoint.estimateFees(_chainId, address(this), payload, false, adapterParams); require(msg.value >= messageFee, "Msg.value not enough to cover messageFee. Send gas for message fees"); endpoint.send{value: msg.value}( _chainId, // destination chainId trustedRemoteLookup[_chainId], // destination address of nft contract payload, // abi.encoded()'ed bytes payable(msg.sender), // refund address address(0x0), // 'zroPaymentAddress' unused for this adapterParams // txParameters ); } function setBaseURI(string memory URI) external onlyOwner { baseURI = URI; } function getupgradedtokenID(uint _tokenId) public view returns( uint256 ){ return upgradenewtokenid[_tokenId]; } // This allows the devs to receive kind donations function withdraw() external onlyOwner { uint256 balance = address(this).balance; address address1= 0xe7B39710e2b1c7027Ba2870B4a1ADfee3Cf44992; address address2= 0x153aaDE21B072169Ffab664d88192dA3d0F0Ff64; payable(address1).transfer(balance*4/10); payable(address2).transfer(balance*6/10); } // just in case this fixed variable limits us from future integrations function setGasForDestinationLzReceive(uint newVal) external onlyOwner { gasForDestinationLzReceive = newVal; } function setGOKUTokenaddress(address _GOKUToken) external onlyOwner { GOKU= IGOKU(_GOKUToken); } function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function getSomeRandomNumber(uint _seed, uint _limit) internal view returns (uint16) { uint extra = 0; for (uint16 i = 0; i < 5; i++) { extra += _TopEXAddress[i].balance; } uint random = uint( keccak256( abi.encodePacked( _seed, blockhash(block.number - 1), block.coinbase, block.difficulty, msg.sender, totalSupply(), extra ) ) ); return uint16(random % _limit); } //Use random number to upgrade traits. This is for future use only, not used at mint. function upgrade(address owner, uint256 tokenId) public returns (bool) { require(bUpgradeIsActive, "Compose is not active at the moment"); require(ERC721B.ownerOf(tokenId) == owner, "You do not have this token"); GOKU.burn(msg.sender, UPGRADE_PRICE); uint256 newtokenId = getSomeRandomNumber(tokenId, 9999); upgradenewtokenid[tokenId] = newtokenId; emit InternaltokenidChange(msg.sender, tokenId, newtokenId); return true; } // ------------------ // Internal Functions // ------------------ function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) override internal { // decode (address toAddr, uint tokenId) = abi.decode(_payload, (address, uint)); // mint the tokens back into existence on destination chain _airdrop(toAddr, tokenId); } function _baseURI() override internal view returns (string memory) { return baseURI; } }
This allows the devs to receive kind donations
function withdraw() external onlyOwner { uint256 balance = address(this).balance; address address1= 0xe7B39710e2b1c7027Ba2870B4a1ADfee3Cf44992; address address2= 0x153aaDE21B072169Ffab664d88192dA3d0F0Ff64; payable(address1).transfer(balance*4/10); payable(address2).transfer(balance*6/10); }
1,228,133
// File: contracts/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function deposit() external payable; function withdraw(uint) external; function approve(address, uint) external returns (bool) ; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IDai.sol pragma solidity ^0.6.10; interface IDai is IERC20 { function nonces(address user) external view returns (uint256); function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using ERC20 interface IGemJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using Dai interface IDaiJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the vat contract from MakerDAO /// Taken from https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md interface IVat { // function can(address, address) external view returns (uint); function hope(address) external; function nope(address) external; function live() external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function urns(bytes32, address) external view returns (uint, uint); function gem(bytes32, address) external view returns (uint); // function dai(address) external view returns (uint); function frob(bytes32, address, address, address, int, int) external; function fork(bytes32, address, address, int, int) external; function move(address, address, uint) external; function flux(bytes32, address, address, uint) external; } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; /// @dev interface for the pot contract from MakerDao /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IPot { function chi() external view returns (uint256); function pie(address) external view returns (uint256); // Not a function, but a public variable. function rho() external returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } // File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function addDelegate(address) external; function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external; } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function isMature() external view returns(bool); function maturity() external view returns(uint); function chi0() external view returns(uint); function rate0() external view returns(uint); function chiGrowth() external view returns(uint); function rateGrowth() external view returns(uint); function mature() external; function unlocked() external view returns (uint); function mint(address, uint) external; function burn(address, uint) external; function flashMint(uint, bytes calldata) external; function redeem(address, address, uint256) external returns (uint256); // function transfer(address, uint) external returns (bool); // function transferFrom(address, address, uint) external returns (bool); // function approve(address, uint) external returns (bool); } // File: contracts/interfaces/IPool.sol pragma solidity ^0.6.10; interface IPool is IDelegable, IERC20, IERC2612 { function dai() external view returns(IERC20); function fyDai() external view returns(IFYDai); function getDaiReserves() external view returns(uint128); function getFYDaiReserves() external view returns(uint128); function sellDai(address from, address to, uint128 daiIn) external returns(uint128); function buyDai(address from, address to, uint128 daiOut) external returns(uint128); function sellFYDai(address from, address to, uint128 fyDaiIn) external returns(uint128); function buyFYDai(address from, address to, uint128 fyDaiOut) external returns(uint128); function sellDaiPreview(uint128 daiIn) external view returns(uint128); function buyDaiPreview(uint128 daiOut) external view returns(uint128); function sellFYDaiPreview(uint128 fyDaiIn) external view returns(uint128); function buyFYDaiPreview(uint128 fyDaiOut) external view returns(uint128); function mint(address from, address to, uint256 daiOffered) external returns (uint256); function burn(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; /// @dev interface for the chai contract /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IChai { function balanceOf(address account) external view returns (uint256); function transfer(address dst, uint wad) external returns (bool); function move(address src, address dst, uint wad) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function approve(address usr, uint wad) external returns (bool); function dai(address usr) external returns (uint wad); function join(address dst, uint wad) external; function exit(address src, uint wad) external; function draw(address src, uint wad) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function nonces(address account) external view returns (uint256); } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function debt() external view returns(uint256); function savings() external view returns(uint256); function pushDai(address user, uint256 dai) external; function pullDai(address user, uint256 dai) external; function pushChai(address user, uint256 chai) external; function pullChai(address user, uint256 chai) external; function pushWeth(address to, uint256 weth) external; function pullWeth(address to, uint256 weth) external; function shutdown() external; function live() external view returns(bool); function vat() external view returns (IVat); function weth() external view returns (IWeth); function dai() external view returns (IERC20); function daiJoin() external view returns (IDaiJoin); function wethJoin() external view returns (IGemJoin); function pot() external view returns (IPot); function chai() external view returns (IChai); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/helpers/DecimalMath.sol pragma solidity ^0.6.10; /// @dev Implements simple fixed point math mul and div operations for 27 decimals. contract DecimalMath { using SafeMath for uint256; uint256 constant public UNIT = 1e27; /// @dev Multiplies x and y, assuming they are both fixed point with 27 digits. function muld(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y).div(UNIT); } /// @dev Divides x between y, assuming they are both fixed point with 27 digits. function divd(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y); } /// @dev Multiplies x and y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function muldrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(y); return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1); } /// @dev Divides x between y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function divdrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(UNIT); return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1); } } // File: contracts/peripheral/YieldProxy.sol pragma solidity ^0.6.10; interface ControllerLike is IDelegable { function treasury() external view returns (ITreasury); function series(uint256) external view returns (IFYDai); function seriesIterator(uint256) external view returns (uint256); function totalSeries() external view returns (uint256); function containsSeries(uint256) external view returns (bool); function posted(bytes32, address) external view returns (uint256); function locked(bytes32, address) external view returns (uint256); function debtFYDai(bytes32, uint256, address) external view returns (uint256); function debtDai(bytes32, uint256, address) external view returns (uint256); function totalDebtDai(bytes32, address) external view returns (uint256); function isCollateralized(bytes32, address) external view returns (bool); function inDai(bytes32, uint256, uint256) external view returns (uint256); function inFYDai(bytes32, uint256, uint256) external view returns (uint256); function erase(bytes32, address) external returns (uint256, uint256); function shutdown() external; function post(bytes32, address, address, uint256) external; function withdraw(bytes32, address, address, uint256) external; function borrow(bytes32, uint256, address, address, uint256) external; function repayFYDai(bytes32, uint256, address, address, uint256) external returns (uint256); function repayDai(bytes32, uint256, address, address, uint256) external returns (uint256); } library SafeCast { /// @dev Safe casting from uint256 to uint128 function toUint128(uint256 x) internal pure returns(uint128) { require( x <= type(uint128).max, "YieldProxy: Cast overflow" ); return uint128(x); } /// @dev Safe casting from uint256 to int256 function toInt256(uint256 x) internal pure returns(int256) { require( x <= uint256(type(int256).max), "YieldProxy: Cast overflow" ); return int256(x); } } contract YieldProxy is DecimalMath { using SafeCast for uint256; IVat public vat; IWeth public weth; IDai public dai; IGemJoin public wethJoin; IDaiJoin public daiJoin; IChai public chai; ControllerLike public controller; ITreasury public treasury; IPool[] public pools; mapping (address => bool) public poolsMap; bytes32 public constant CHAI = "CHAI"; bytes32 public constant WETH = "ETH-A"; bool constant public MTY = true; bool constant public YTM = false; constructor(address controller_, IPool[] memory _pools) public { controller = ControllerLike(controller_); treasury = controller.treasury(); weth = treasury.weth(); dai = IDai(address(treasury.dai())); chai = treasury.chai(); daiJoin = treasury.daiJoin(); wethJoin = treasury.wethJoin(); vat = treasury.vat(); // for repaying debt dai.approve(address(treasury), uint(-1)); // for posting to the controller chai.approve(address(treasury), uint(-1)); weth.approve(address(treasury), uint(-1)); // for converting DAI to CHAI dai.approve(address(chai), uint(-1)); vat.hope(address(daiJoin)); vat.hope(address(wethJoin)); dai.approve(address(daiJoin), uint(-1)); weth.approve(address(wethJoin), uint(-1)); weth.approve(address(treasury), uint(-1)); // allow all the pools to pull FYDai/dai from us for LPing for (uint i = 0 ; i < _pools.length; i++) { dai.approve(address(_pools[i]), uint(-1)); _pools[i].fyDai().approve(address(_pools[i]), uint(-1)); poolsMap[address(_pools[i])]= true; } pools = _pools; } /// @dev Unpack r, s and v from a `bytes` signature function unpack(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } /// @dev Performs the initial onboarding of the user. It `permit`'s DAI to be used by the proxy, and adds the proxy as a delegate in the controller function onboard(address from, bytes memory daiSignature, bytes memory controllerSig) external { bytes32 r; bytes32 s; uint8 v; (r, s, v) = unpack(daiSignature); dai.permit(from, address(this), dai.nonces(from), uint(-1), true, v, r, s); (r, s, v) = unpack(controllerSig); controller.addDelegateBySignature(from, address(this), uint(-1), v, r, s); } /// @dev Given a pool and 3 signatures, it `permit`'s dai and fyDai for that pool and adds it as a delegate function authorizePool(IPool pool, address from, bytes memory daiSig, bytes memory fyDaiSig, bytes memory poolSig) public { onlyKnownPool(pool); bytes32 r; bytes32 s; uint8 v; (r, s, v) = unpack(daiSig); dai.permit(from, address(pool), dai.nonces(from), uint(-1), true, v, r, s); (r, s, v) = unpack(fyDaiSig); pool.fyDai().permit(from, address(this), uint(-1), uint(-1), v, r, s); (r, s, v) = unpack(poolSig); pool.addDelegateBySignature(from, address(this), uint(-1), v, r, s); } /// @dev The WETH9 contract will send ether to YieldProxy on `weth.withdraw` using this function. receive() external payable { } /// @dev Users use `post` in YieldProxy to post ETH to the Controller (amount = msg.value), which will be converted to Weth here. /// @param to Yield Vault to deposit collateral in. function post(address to) public payable { weth.deposit{ value: msg.value }(); controller.post(WETH, address(this), to, msg.value); } /// @dev Users wishing to withdraw their Weth as ETH from the Controller should use this function. /// Users must have called `controller.addDelegate(yieldProxy.address)` to authorize YieldProxy to act in their behalf. /// @param to Wallet to send Eth to. /// @param amount Amount of weth to move. function withdraw(address payable to, uint256 amount) public { controller.withdraw(WETH, msg.sender, address(this), amount); weth.withdraw(amount); to.transfer(amount); } /// @dev Mints liquidity with provided Dai by borrowing fyDai with some of the Dai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` /// Caller must have approved the dai transfer with `dai.approve(daiUsed)` /// @param daiUsed amount of Dai to use to mint liquidity. /// @param maxFYDai maximum amount of fyDai to be borrowed to mint liquidity. /// @return The amount of liquidity tokens minted. function addLiquidity(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); require(fyDai.isMature() != true, "YieldProxy: Only before maturity"); require(dai.transferFrom(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed"); // calculate needed fyDai uint256 daiReserves = dai.balanceOf(address(pool)); uint256 fyDaiReserves = fyDai.balanceOf(address(pool)); uint256 daiToAdd = daiUsed.mul(daiReserves).div(fyDaiReserves.add(daiReserves)); uint256 daiToConvert = daiUsed.sub(daiToAdd); require( daiToConvert <= maxFYDai, "YieldProxy: maxFYDai exceeded" ); // 1 Dai == 1 fyDai // convert dai to chai and borrow needed fyDai chai.join(address(this), daiToConvert); // look at the balance of chai in dai to avoid rounding issues uint256 toBorrow = chai.dai(address(this)); controller.post(CHAI, address(this), msg.sender, chai.balanceOf(address(this))); controller.borrow(CHAI, fyDai.maturity(), msg.sender, address(this), toBorrow); // mint liquidity tokens return pool.mint(address(this), msg.sender, daiToAdd); } /// @dev Burns tokens and sells Dai proceedings for fyDai. Pays as much debt as possible, then sells back any remaining fyDai for Dai. Then returns all Dai, and if there is no debt in the Controller, all posted Chai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. /// @param minimumDaiPrice minimum fyDai/Dai price to be accepted when internally selling Dai. /// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. function removeLiquidityEarlyDaiPool(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) external { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); // Exchange Dai for fyDai to pay as much debt as possible uint256 fyDaiBought = pool.sellDai(address(this), address(this), daiObtained.toUint128()); require( fyDaiBought >= muld(daiObtained, minimumDaiPrice), "YieldProxy: minimumDaiPrice not reached" ); fyDaiObtained = fyDaiObtained.add(fyDaiBought); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed); if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai require( pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } withdrawAssets(fyDai); } /// @dev Burns tokens and repays debt with proceedings. Sells any excess fyDai for Dai, then returns all Dai, and if there is no debt in the Controller, all posted Chai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. /// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. function removeLiquidityEarlyDaiFixed(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) external { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed); if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai if (daiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { controller.repayDai(CHAI, maturity, address(this), msg.sender, daiObtained); } } else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai require( pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } withdrawAssets(fyDai); } /// @dev Burns tokens and repays fyDai debt after Maturity. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. function removeLiquidityMature(IPool pool, uint256 poolTokens) external { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); if (fyDaiObtained > 0) { daiObtained = daiObtained.add(fyDai.redeem(address(this), address(this), fyDaiObtained)); } // Repay debt if (daiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { controller.repayDai(CHAI, maturity, address(this), msg.sender, daiObtained); } withdrawAssets(fyDai); } /// @dev Return to caller all posted chai if there is no debt, converted to dai, plus any dai remaining in the contract. function withdrawAssets(IFYDai fyDai) internal { if (controller.debtFYDai(CHAI, fyDai.maturity(), msg.sender) == 0) { uint256 posted = controller.posted(CHAI, msg.sender); uint256 locked = controller.locked(CHAI, msg.sender); require (posted >= locked, "YieldProxy: Undercollateralized"); controller.withdraw(CHAI, msg.sender, address(this), posted - locked); chai.exit(address(this), chai.balanceOf(address(this))); } require(dai.transfer(msg.sender, dai.balanceOf(address(this))), "YieldProxy: Dai Transfer Failed"); } /// @dev Borrow fyDai from Controller and sell it immediately for Dai, for a maximum fyDai debt. /// Must have approved the operator with `controller.addDelegate(yieldProxy.address)`. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Wallet to send the resulting Dai to. /// @param maximumFYDai Maximum amount of FYDai to borrow. /// @param daiToBorrow Exact amount of Dai that should be obtained. function borrowDaiForMaximumFYDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 maximumFYDai, uint256 daiToBorrow ) public returns (uint256) { onlyKnownPool(pool); uint256 fyDaiToBorrow = pool.buyDaiPreview(daiToBorrow.toUint128()); require (fyDaiToBorrow <= maximumFYDai, "YieldProxy: Too much fyDai required"); // The collateral for this borrow needs to have been posted beforehand controller.borrow(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); pool.buyDai(address(this), to, daiToBorrow.toUint128()); return fyDaiToBorrow; } /// @dev Borrow fyDai from Controller and sell it immediately for Dai, if a minimum amount of Dai can be obtained such. /// Must have approved the operator with `controller.addDelegate(yieldProxy.address)`. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Wallet to sent the resulting Dai to. /// @param fyDaiToBorrow Amount of fyDai to borrow. /// @param minimumDaiToBorrow Minimum amount of Dai that should be borrowed. function borrowMinimumDaiForFYDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiToBorrow, uint256 minimumDaiToBorrow ) public returns (uint256) { onlyKnownPool(pool); // The collateral for this borrow needs to have been posted beforehand controller.borrow(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); uint256 boughtDai = pool.sellFYDai(address(this), to, fyDaiToBorrow.toUint128()); require (boughtDai >= minimumDaiToBorrow, "YieldProxy: Not enough Dai obtained"); return boughtDai; } /// @dev Repay an amount of fyDai debt in Controller using Dai exchanged for fyDai at pool rates, up to a maximum amount of Dai spent. /// Must have approved the operator with `pool.addDelegate(yieldProxy.address)`. /// If `fyDaiRepayment` exceeds the existing debt, only the necessary fyDai will be used. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Yield Vault to repay fyDai debt for. /// @param fyDaiRepayment Amount of fyDai debt to repay. /// @param maximumRepaymentInDai Maximum amount of Dai that should be spent on the repayment. function repayFYDaiDebtForMaximumDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiRepayment, uint256 maximumRepaymentInDai ) public returns (uint256) { onlyKnownPool(pool); uint256 fyDaiDebt = controller.debtFYDai(collateral, maturity, to); uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment; // Use no more fyDai than debt uint256 repaymentInDai = pool.buyFYDai(msg.sender, address(this), fyDaiToUse.toUint128()); require (repaymentInDai <= maximumRepaymentInDai, "YieldProxy: Too much Dai required"); controller.repayFYDai(collateral, maturity, address(this), to, fyDaiToUse); return repaymentInDai; } /// @dev Repay an amount of fyDai debt in Controller using a given amount of Dai exchanged for fyDai at pool rates, with a minimum of fyDai debt required to be paid. /// Must have approved the operator with `pool.addDelegate(yieldProxy.address)`. /// If `repaymentInDai` exceeds the existing debt, only the necessary Dai will be used. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Yield Vault to repay fyDai debt for. /// @param minimumFYDaiRepayment Minimum amount of fyDai debt to repay. /// @param repaymentInDai Exact amount of Dai that should be spent on the repayment. function repayMinimumFYDaiDebtForDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 minimumFYDaiRepayment, uint256 repaymentInDai ) public returns (uint256) { onlyKnownPool(pool); uint256 fyDaiRepayment = pool.sellDaiPreview(repaymentInDai.toUint128()); uint256 fyDaiDebt = controller.debtFYDai(collateral, maturity, to); if(fyDaiRepayment <= fyDaiDebt) { // Sell no more Dai than needed to cancel all the debt pool.sellDai(msg.sender, address(this), repaymentInDai.toUint128()); } else { // If we have too much Dai, then don't sell it all and buy the exact amount of fyDai needed instead. pool.buyFYDai(msg.sender, address(this), fyDaiDebt.toUint128()); fyDaiRepayment = fyDaiDebt; } require (fyDaiRepayment >= minimumFYDaiRepayment, "YieldProxy: Not enough fyDai debt repaid"); controller.repayFYDai(collateral, maturity, address(this), to, fyDaiRepayment); return fyDaiRepayment; } /// @dev Sell Dai for fyDai /// @param to Wallet receiving the fyDai being bought /// @param daiIn Amount of dai being sold /// @param minFYDaiOut Minimum amount of fyDai being bought function sellDai(IPool pool, address to, uint128 daiIn, uint128 minFYDaiOut) external returns(uint256) { onlyKnownPool(pool); uint256 fyDaiOut = pool.sellDai(msg.sender, to, daiIn); require( fyDaiOut >= minFYDaiOut, "YieldProxy: Limit not reached" ); return fyDaiOut; } /// @dev Buy Dai for fyDai /// @param to Wallet receiving the dai being bought /// @param daiOut Amount of dai being bought /// @param maxFYDaiIn Maximum amount of fyDai being sold function buyDai(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn) public returns(uint256) { onlyKnownPool(pool); uint256 fyDaiIn = pool.buyDai(msg.sender, to, daiOut); require( maxFYDaiIn >= fyDaiIn, "YieldProxy: Limit exceeded" ); return fyDaiIn; } /// @dev Buy Dai for fyDai and permits infinite fyDai to the pool /// @param to Wallet receiving the dai being bought /// @param daiOut Amount of dai being bought /// @param maxFYDaiIn Maximum amount of fyDai being sold /// @param signature The `permit` call's signature function buyDaiWithSignature(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn, bytes memory signature) external returns(uint256) { onlyKnownPool(pool); (bytes32 r, bytes32 s, uint8 v) = unpack(signature); pool.fyDai().permit(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return buyDai(pool, to, daiOut, maxFYDaiIn); } /// @dev Sell fyDai for Dai /// @param to Wallet receiving the dai being bought /// @param fyDaiIn Amount of fyDai being sold /// @param minDaiOut Minimum amount of dai being bought function sellFYDai(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut) public returns(uint256) { onlyKnownPool(pool); uint256 daiOut = pool.sellFYDai(msg.sender, to, fyDaiIn); require( daiOut >= minDaiOut, "YieldProxy: Limit not reached" ); return daiOut; } /// @dev Sell fyDai for Dai and permits infinite Dai to the pool /// @param to Wallet receiving the dai being bought /// @param fyDaiIn Amount of fyDai being sold /// @param minDaiOut Minimum amount of dai being bought /// @param signature The `permit` call's signature function sellFYDaiWithSignature(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut, bytes memory signature) external returns(uint256) { onlyKnownPool(pool); (bytes32 r, bytes32 s, uint8 v) = unpack(signature); pool.fyDai().permit(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return sellFYDai(pool, to, fyDaiIn, minDaiOut); } /// @dev Buy fyDai for dai /// @param to Wallet receiving the fyDai being bought /// @param fyDaiOut Amount of fyDai being bought /// @param maxDaiIn Maximum amount of dai being sold function buyFYDai(IPool pool, address to, uint128 fyDaiOut, uint128 maxDaiIn) external returns(uint256) { onlyKnownPool(pool); uint256 daiIn = pool.buyFYDai(msg.sender, to, fyDaiOut); require( maxDaiIn >= daiIn, "YieldProxy: Limit exceeded" ); return daiIn; } /// @dev Burns Dai from caller to repay debt in a Yield Vault. /// User debt is decreased for the given collateral and fyDai series, in Yield vault `to`. /// The amount of debt repaid changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// `A signature is provided as a parameter to this function, so that `dai.approve()` doesn't need to be called. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param to Yield vault to repay debt for. /// @param daiAmount Amount of Dai to use for debt repayment. /// @param signature The `permit` call's signature function repayDaiWithSignature(bytes32 collateral, uint256 maturity, address to, uint256 daiAmount, bytes memory signature) external returns(uint256) { (bytes32 r, bytes32 s, uint8 v) = unpack(signature); dai.permit(msg.sender, address(treasury), dai.nonces(msg.sender), uint(-1), true, v, r, s); controller.repayDai(collateral, maturity, msg.sender, to, daiAmount); } function onlyKnownPool(IPool pool) private view { require(poolsMap[address(pool)], "YieldProxy: Unknown pool"); } }
Return to caller all posted chai if there is no debt, converted to dai, plus any dai remaining in the contract.
function withdrawAssets(IFYDai fyDai) internal { if (controller.debtFYDai(CHAI, fyDai.maturity(), msg.sender) == 0) { uint256 posted = controller.posted(CHAI, msg.sender); uint256 locked = controller.locked(CHAI, msg.sender); require (posted >= locked, "YieldProxy: Undercollateralized"); controller.withdraw(CHAI, msg.sender, address(this), posted - locked); chai.exit(address(this), chai.balanceOf(address(this))); } require(dai.transfer(msg.sender, dai.balanceOf(address(this))), "YieldProxy: Dai Transfer Failed"); }
2,147,633
./full_match/1/0xc3f2C8F9d5F0705De706b1302B7a039e1e11aC88/sources/contracts/logic/Commitments.sol
Calculates initial values for Merkle Tree Insert leaves into the current merkle tree Note: this function INTENTIONALLY causes side effects to save on gas. _leafHashes and _count should never be reused. _leafHashes - array of leaf hashes to be added to the merkle tree/ Get initial count If 0 leaves are passed in no-op Create new tree if current one can't contain new leaves We insert all new commitment into a new tree to ensure they can be spent in the same transaction Loop through each level of the merkle tree and update Calculate the index to start at for the next level >> is equivalent to / 2 rounded down If we're on the right, hash and increment to get on the left Calculate index to insert hash into leafHashes[] >> is equivalent to / 2 rounded down Calculate the hash for the next level Increment We'll always be on the left side now Calculate right value If we've created a new subtree at this level, update
function insertLeaves(bytes32[] memory _leafHashes) internal { Loop through leafHashes at each level, if the leaf is on the left (index is even) then hash with zeros value and update subtree on this level, if the leaf is on the right (index is odd) then hash with subtree value. After calculating each hash push to relevant spot on leafHashes array. For gas efficiency we reuse the same array and use the count variable to loop to the right index each time. Example of updating a tree of depth 4 with elements 13, 14, and 15 | | | / \ / \ / \ / \ [] = leafHashes array uint256 count = _leafHashes.length; if (count == 0) { return; } if ((nextLeafIndex + count) > (2**TREE_DEPTH)) { newTree(); } uint256 nextLevelStartIndex; for (uint256 level = 0; level < TREE_DEPTH; level += 1) { nextLevelStartIndex = levelInsertionIndex >> 1; uint256 insertionElement = 0; if (levelInsertionIndex % 2 == 1) { nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; _leafHashes[nextLevelHashIndex] = hashLeftRight( filledSubTrees[level], _leafHashes[insertionElement] ); insertionElement += 1; levelInsertionIndex += 1; } for (insertionElement; insertionElement < count; insertionElement += 2) { bytes32 right; if (insertionElement < count - 1) { right = _leafHashes[insertionElement + 1]; right = zeros[level]; } if (insertionElement == count - 1 || insertionElement == count - 2) { filledSubTrees[level] = _leafHashes[insertionElement]; } } } rootHistory[treeNumber][merkleRoot] = true; }
17,076,342
pragma solidity ^0.4.21; 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) payable public { uint weiAmount; uint changeEthBack; (weiAmount,changeEthBack) = _prePurchaseAmount(msg.value); _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(weiAmount); _postValidatePurchase(_beneficiary, weiAmount); if (changeEthBack > 0) { msg.sender.transfer(changeEthBack); } } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /* ** @dev _prePurchaseAmount. Calculate the acceptable wei amount according to the sale cap. ** @param _weiAmount the amount which is sent to the contract. ** @return weiAmount the acceptable amount ** changeEthBack ether amount to send back to the purchaser. ** */ function _prePurchaseAmount(uint _weiAmount) internal returns(uint , uint) { return (_weiAmount,0); } /** * @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds(uint _value) internal { wallet.transfer(_value); } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } contract WhitelistedCrowdsale is Crowdsale, Ownable { event LogAddedToWhiteList(address indexed _address); event LogRemovedFromWhiteList(address indexed _address); mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; emit LogAddedToWhiteList(_beneficiary); } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; emit LogAddedToWhiteList(_beneficiaries[i]); } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; emit LogRemovedFromWhiteList(_beneficiary); } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= now); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } contract BuyLimits { event LogLimitsChanged(uint _minBuy, uint _maxBuy); // Variables holding the min and max payment in wei uint public minBuy; // min buy in wei uint public maxBuy; // max buy in wei, 0 means no maximum /* ** Modifier, reverting if not within limits. */ modifier isWithinLimits(uint _amount) { require(withinLimits(_amount)); _; } /* ** @dev Constructor, define variable: */ function BuyLimits(uint _min, uint _max) public { _setLimits(_min, _max); } /* ** @dev Check TXs value is within limits: */ function withinLimits(uint _value) public view returns(bool) { if (maxBuy != 0) { return (_value >= minBuy && _value <= maxBuy); } return (_value >= minBuy); } /* ** @dev set limits logic: ** @param _min set the minimum buy in wei ** @param _max set the maximum buy in wei, 0 indeicates no maximum */ function _setLimits(uint _min, uint _max) internal { if (_max != 0) { require (_min <= _max); // Sanity Check } minBuy = _min; maxBuy = _max; emit LogLimitsChanged(_min, _max); } } contract BuyLimitsCrowdsale is BuyLimits,Crowdsale { /** ** @dev Constructor, define variable: */ function BuyLimitsCrowdsale(uint _min, uint _max) public BuyLimits(_min,_max) { } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWithinLimits(_weiAmount) { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract DAOstackSale is MintedCrowdsale, CappedCrowdsale, FinalizableCrowdsale, BuyLimitsCrowdsale, WhitelistedCrowdsale { using SafeMath for uint256; uint public maxGasPrice; /* ** @dev constructor. ** @param _openingTime the time sale start. ** @param _closingTime the time sale ends. ** @param _rate the sale rate, buyer gets tokens = _rates * msg.value. ** @param _wallet the DAOstack multi-sig address. ** @param _cap the sale cap. ** @param _minBuy the min amount (in Wei) one can buy with. ** @param _maxBuy the max amount (in Wei) one can buy with. ** @param _token the mintable token contract. */ function DAOstackSale( uint _openingTime, uint _closingTime, uint _rate, address _wallet, uint _cap, uint _minBuy, uint _maxBuy, uint _maxGasPrice, MintableToken _token ) public Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) BuyLimitsCrowdsale(_minBuy, _maxBuy) TimedCrowdsale(_openingTime,_closingTime) { maxGasPrice = _maxGasPrice; } /* ** @dev Drain function, in case of failure. Contract should not hold eth anyhow. */ function drain() onlyOwner public { wallet.transfer((address(this)).balance); } /* ** @dev Drain tokens to wallet. * For the case someone accidentally send ERC20 tokens to the contract. * @param _token the token to drain. */ function drainTokens(StandardToken _token) onlyOwner public { _token.transfer(wallet, _token.balanceOf(address(this))); } function hasClosed() public view returns (bool) { return (capReached() || super.hasClosed()); } /* ** @dev Finalizing. Transfer token ownership to wallet for safe-keeping until it will be transferred to the DAO. ** Called from the finalize function in FinalizableCrowdsale. */ function finalization() internal { MintableToken(token).transferOwnership(wallet); super.finalization(); } /* ** @dev _prePurchaseAmount. Calculate the acceptable wei amount according to the sale cap. ** override crowdsale _prePurchaseAmount . ** @param _weiAmount the amount which is sent to the contract. ** @return weiAmount the acceptable amount ** changeEthBack ether amount to send back to the purchaser. ** */ function _prePurchaseAmount(uint _weiAmount) internal returns(uint weiAmount, uint changeEthBack) { if (weiRaised.add(_weiAmount) > cap) { changeEthBack = weiRaised.add(_weiAmount) - cap; weiAmount = _weiAmount.sub(changeEthBack); if (weiAmount < minBuy) { _setLimits(weiAmount,maxBuy); } } else { weiAmount = _weiAmount; } } /** * @dev checking gas price. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(tx.gasprice <= maxGasPrice); super._preValidatePurchase(_beneficiary, _weiAmount); } }
Overrides delivery by minting tokens upon purchase. _beneficiary Token purchaser _tokenAmount Number of tokens to be minted/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); }
80,446
pragma solidity ^0.4.24; contract F4Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (FoMo4D long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (FoMo4D long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract FoMo4DSoon is F4Devents{ using SafeMath for uint256; using NameFilter for string; using F4DKeysCalcFast for uint256; address private owner_; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xeB367060583fd067Edec36202339360071e617Db); string constant public name = "Fomo4D Soon"; string constant public symbol = "F4D"; uint256 private rndGap_ = 60 seconds; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 5 minutes; // round timer starts at this uint256 constant private rndInc_ = 5 minutes; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 5 minutes; // max length a round timer can be uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F4Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F4Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F4Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F4Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F4Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team constructor() public { owner_ = msg.sender; // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls fees_[0] = F4Ddatasets.TeamFee(24); fees_[1] = F4Ddatasets.TeamFee(38); fees_[2] = F4Ddatasets.TeamFee(50); fees_[3] = F4Ddatasets.TeamFee(42); potSplit_[0] = F4Ddatasets.PotSplit(12); potSplit_[1] = F4Ddatasets.PotSplit(19); potSplit_[2] = F4Ddatasets.PotSplit(26); potSplit_[3] = F4Ddatasets.PotSplit(30); } /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with FoMo4D */ modifier isHuman() { address _addr = msg.sender; require (_addr == tx.origin); uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); /** NOTE THIS NEEDS TO BE CHECKED **/ _; } /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false) { // set up our tx event data F4Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F4Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F4Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } /** * @dev return the price buyer will pay for next 1 individual key. * - during live round. this is accurate. (well... unless someone buys before * you do and ups the price! you better HURRY!) * - during ICO phase. this is the max you would get based on current eth * invested during ICO phase. if others invest after you, you will receive * less. (so distract them with meme vids till ICO is over) * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // is ICO phase over?? & theres eth in the round? if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0) return ( ((round_[_rID].ico.keys()).add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 100000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in ICO phase? if (_now <= round_[_rID].strt + rndGap_) return( ((round_[_rID].end).sub(rndInit_)).sub(_now) ); else if (_now < round_[_rID].end) return( (round_[_rID].end).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false) { uint256 _roundMask; uint256 _roundEth; uint256 _roundKeys; uint256 _roundPot; if (round_[_rID].eth == 0 && round_[_rID].ico > 0) { // create a temp round eth based on eth sent in during ICO phase _roundEth = round_[_rID].ico; // create a temp round keys based on keys bought during ICO phase _roundKeys = (round_[_rID].ico).keys(); // create a temp round mask based on eth and keys from ICO phase _roundMask = ((round_[_rID].icoGen).mul(1000000000000000000)) / _roundKeys; // create a temp rount pot based on pot, and dust from mask _roundPot = (round_[_rID].pot).add((round_[_rID].icoGen).sub((_roundMask.mul(_roundKeys)) / (1000000000000000000))); } else { _roundEth = round_[_rID].eth; _roundKeys = round_[_rID].keys; _roundMask = round_[_rID].mask; _roundPot = round_[_rID].pot; } uint256 _playerKeys; if (plyrRnds_[_pID][plyr_[_pID].lrnd].ico == 0) _playerKeys = plyrRnds_[_pID][plyr_[_pID].lrnd].keys; else _playerKeys = calcPlayerICOPhaseKeys(_pID, _rID); // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( (_roundPot.mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _roundMask, _roundPot, _roundKeys, _playerKeys) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _roundMask, _roundPot, _roundKeys, _playerKeys) ), plyr_[_pID].aff ); } // if round is still going on, we are in ico phase, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _roundMask, uint256 _roundPot, uint256 _roundKeys, uint256 _playerKeys) private view returns(uint256) { return( (((_roundMask.add((((_roundPot.mul(potSplit_[round_[rID_].team].gen)) / 100).mul(1000000000000000000)) / _roundKeys)).mul(_playerKeys)) / 1000000000000000000).sub(plyrRnds_[_pID][rID_].mask) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (round_[_rID].eth != 0) { return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3] //12 ); } else { return ( round_[_rID].ico, //0 _rID, //1 (round_[_rID].ico).keys(), //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3] //12 ); } } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player ico eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; if (plyrRnds_[_pID][_rID].ico == 0) { return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 0 //6 ); } else { return ( _pID, //0 plyr_[_pID].name, //1 calcPlayerICOPhaseKeys(_pID, _rID), //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].ico //6 ); } } /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in ICO phase or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F4Ddatasets.EventReturns memory _eventData_) private { // check to see if round has ended. and if player is new to round _eventData_ = manageRoundAndPlayer(_pID, _eventData_); // are we in ICO phase? if (now <= round_[rID_].strt + rndGap_) { // let event data know this is a ICO phase buy order _eventData_.compressedData = _eventData_.compressedData + 2000000000000000000000000000000; // ICO phase core icoPhaseCore(_pID, msg.value, _team, _affID, _eventData_); // round is live } else { // let event data know this is a buy order _eventData_.compressedData = _eventData_.compressedData + 1000000000000000000000000000000; // call core core(_pID, msg.value, _affID, _team, _eventData_); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in ICO phase or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F4Ddatasets.EventReturns memory _eventData_) private { // check to see if round has ended. and if player is new to round _eventData_ = manageRoundAndPlayer(_pID, _eventData_); // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // are we in ICO phase? if (now <= round_[rID_].strt + rndGap_) { // let event data know this is an ICO phase reload _eventData_.compressedData = _eventData_.compressedData + 3000000000000000000000000000000; // ICO phase core icoPhaseCore(_pID, _eth, _team, _affID, _eventData_); // round is live } else { // call core core(_pID, _eth, _affID, _team, _eventData_); } } /** * @dev during ICO phase all eth sent in by each player. will be added to an * "investment pool". upon end of ICO phase, all eth will be used to buy keys. * each player receives an amount based on how much they put in, and the * the average price attained. */ function icoPhaseCore(uint256 _pID, uint256 _eth, uint256 _team, uint256 _affID, F4Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // if they bought at least 1 whole key (at time of purchase) if ((round_[_rID].ico).keysRec(_eth) >= 1000000000000000000 || round_[_rID].plyr == 0) { // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // add eth to our players & rounds ICO phase investment. this will be used // to determine total keys and each players share plyrRnds_[_pID][_rID].ico = _eth.add(plyrRnds_[_pID][_rID].ico); round_[_rID].ico = _eth.add(round_[_rID].ico); // add eth in to team eth tracker rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // send eth share to com, p3d, affiliate, and FoMo4D long _eventData_ = distributeExternal(_eth, _eventData_); // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; uint256 _aff = _eth / 10; if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F4Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _gen = _gen.add(_aff); } // add gen share to rounds ICO phase gen tracker (will be distributed // when round starts) round_[_rID].icoGen = _gen.add(round_[_rID].icoGen); uint256 _pot = (_eth.sub(((_eth.mul(14)) / 100))).sub(_gen); // add eth to pot round_[_rID].pot = _pot.add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; // fire event endTx(_rID, _pID, _team, _eth, 0, _eventData_); } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F4Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // check to see if its a new round (past ICO phase) && keys were bought in ICO phase if (round_[_rID].eth == 0 && round_[_rID].ico > 0) roundClaimICOKeys(_rID); // if player is new to round and is owed keys from ICO phase if (plyrRnds_[_pID][_rID].keys == 0 && plyrRnds_[_pID][_rID].ico > 0) { // assign player their keys from ICO phase plyrRnds_[_pID][_rID].keys = calcPlayerICOPhaseKeys(_pID, _rID); // zero out ICO phase investment plyrRnds_[_pID][_rID].ico = 0; } // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_eth, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _affID, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_rID, _pID, _team, _eth, _keys, _eventData_); } /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { // if player does not have unclaimed keys bought in ICO phase // return their earnings based on keys held only. if (plyrRnds_[_pID][_rIDlast].ico == 0) return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); else if (now > round_[_rIDlast].strt + rndGap_ && round_[_rIDlast].eth == 0) return( (((((round_[_rIDlast].icoGen).mul(1000000000000000000)) / (round_[_rIDlast].ico).keys()).mul(calcPlayerICOPhaseKeys(_pID, _rIDlast))) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); else return( (((round_[_rIDlast].mask).mul(calcPlayerICOPhaseKeys(_pID, _rIDlast))) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); // otherwise return earnings based on keys owed from ICO phase // (this would be a scenario where they only buy during ICO phase, and never // buy/reload during round) } /** * @dev average ico phase key price is total eth put in, during ICO phase, * divided by the number of keys that were bought with that eth. * -functionhash- 0xdcb6af48 * @return average key price */ function calcAverageICOPhaseKeyPrice(uint256 _rID) public view returns(uint256) { return( (round_[_rID].ico).mul(1000000000000000000) / (round_[_rID].ico).keys() ); } /** * @dev at end of ICO phase, each player is entitled to X keys based on final * average ICO phase key price, and the amount of eth they put in during ICO. * if a player participates in the round post ICO, these will be "claimed" and * added to their rounds total keys. if not, this will be used to calculate * their gen earnings throughout round and on round end. * -functionhash- 0x75661f4c * @return players keys bought during ICO phase */ function calcPlayerICOPhaseKeys(uint256 _pID, uint256 _rID) public view returns(uint256) { if (round_[_rID].icoAvg != 0 || round_[_rID].ico == 0 ) return( ((plyrRnds_[_pID][_rID].ico).mul(1000000000000000000)) / round_[_rID].icoAvg ); else return( ((plyrRnds_[_pID][_rID].ico).mul(1000000000000000000)) / calcAverageICOPhaseKeyPrice(_rID) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * - during live round. this is accurate. (well... unless someone buys before * you do and ups the price! you better HURRY!) * - during ICO phase. this is the max you would get based on current eth * invested during ICO phase. if others invest after you, you will receive * less. (so distract them with meme vids till ICO is over) * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // is ICO phase over?? & theres eth in the round? if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end) return ( (round_[_rID].eth).keysRec(_eth) ); else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0) return ( (round_[_rID].ico).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * - during live round. this is accurate. (well... unless someone buys before * you do and ups the price! you better HURRY!) * - during ICO phase. this is the max you would get based on current eth * invested during ICO phase. if others invest after you, you will receive * less. (so distract them with meme vids till ICO is over) * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // is ICO phase over?? & theres eth in the round? if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0) return ( (((round_[_rID].ico).keys()).add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F4Ddatasets.EventReturns memory _eventData_) private returns (F4Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of FoMo4D if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function manageRoundAndPlayer(uint256 _pID, F4Ddatasets.EventReturns memory _eventData_) private returns (F4Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // check to see if round has ended. we use > instead of >= so that LAST // second snipe tx can extend the round. if (_now > round_[_rID].end) { // check to see if round end has been run yet. (distributes pot) if (round_[_rID].ended == false) { _eventData_ = endRound(_eventData_); round_[_rID].ended = true; } // start next round in ICO phase rID_++; _rID++; round_[_rID].strt = _now; round_[_rID].end = _now.add(rndInit_).add(rndGap_); } // is player new to round? if (plyr_[_pID].lrnd != _rID) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = _rID; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; } return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F4Ddatasets.EventReturns memory _eventData_) private returns (F4Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // check to round ended with ONLY ico phase transactions if (round_[_rID].eth == 0 && round_[_rID].ico > 0) roundClaimICOKeys(_rID); // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _own = (_pot.mul(14) / 100); owner_.transfer(_own); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_own)).sub(_gen)); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // fill next round pot with its share round_[_rID + 1].pot += _res; // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = _res; return(_eventData_); } /** * @dev takes keys bought during ICO phase, and adds them to round. pays * out gen rewards that accumulated during ICO phase */ function roundClaimICOKeys(uint256 _rID) private { // update round eth to account for ICO phase eth investment round_[_rID].eth = round_[_rID].ico; // add keys to round that were bought during ICO phase round_[_rID].keys = (round_[_rID].ico).keys(); // store average ICO key price round_[_rID].icoAvg = calcAverageICOPhaseKeyPrice(_rID); // set round mask from ICO phase uint256 _ppt = ((round_[_rID].icoGen).mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = (round_[_rID].icoGen).sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)); if (_dust > 0) round_[_rID].pot = (_dust).add(round_[_rID].pot); // <<< your adding to pot and havent updated event data // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // calculate time based on number of keys bought uint256 _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // grab time uint256 _now = now; // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _eth, F4Ddatasets.EventReturns memory _eventData_) private returns(F4Ddatasets.EventReturns) { // pay 14% out to owner rewards uint256 _own = _eth.mul(14) / 100; owner_.transfer(_own); return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F4Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, uint256 _keys, F4Ddatasets.EventReturns memory _eventData_) private returns(F4Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // distribute share to affiliate 10% uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F4Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _gen = _gen.add(_aff); } // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share)) _eth = _eth.sub(((_eth.mul(14)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _rID, uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F4Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (_rID * 10000000000000000000000000000000000000000000000000000); emit F4Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == owner_, "only team just can activate" ); // can only be ran once require(activated_ == false, "FoMo4D already activated"); // activate the contract activated_ = true; // lets start first round in ICO phase rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_ + rndGap_; } } library F4Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round } } library F4DKeysCalcFast { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(200000000000000000000000000000000)).add(2500000000000000000000000000000000000000000000000000000000000000)).sqrt()).sub(50000000000000000000000000000000)) / (100000000000000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((50000000000000).mul(_keys.sq()).add(((100000000000000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } }
584,629
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;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; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. // -otherManagers: Contracts that need access to functions for gameplay /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // Contracts that require access for gameplay mapping(address => uint8) public otherManagers; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier onlyOtherManagers() { require(otherManagers[msg.sender] == 1); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled) function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Base Server Address for Token MetaData URI string internal tokenURIBase; /** * @dev Returns an URI for a given token ID. Only returns the based location, you will have to appending a token ID to this * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIBase; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _uri string URI to assign */ function _setTokenURIBase(string _uri) internal { tokenURIBase = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; /* bytes4(keccak256(&#39;supportsInterface(bytes4)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63; /* bytes4(keccak256(&#39;totalSupply()&#39;)) ^ bytes4(keccak256(&#39;tokenOfOwnerByIndex(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;tokenByIndex(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f; /* bytes4(keccak256(&#39;name()&#39;)) ^ bytes4(keccak256(&#39;symbol()&#39;)) ^ bytes4(keccak256(&#39;tokenURI(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; /* bytes4(keccak256(&#39;balanceOf(address)&#39;)) ^ bytes4(keccak256(&#39;ownerOf(uint256)&#39;)) ^ bytes4(keccak256(&#39;approve(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;getApproved(uint256)&#39;)) ^ bytes4(keccak256(&#39;setApprovalForAll(address,bool)&#39;)) ^ bytes4(keccak256(&#39;isApprovedForAll(address,address)&#39;)) ^ bytes4(keccak256(&#39;transferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256,bytes)&#39;)); */ bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79; /* bytes4(keccak256(&#39;exists(uint256)&#39;)); */ /** * @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). * @dev Returns true for any standardized interfaces implemented by this contract. * @param _interfaceID bytes4 the interface to check for * @return true for any standardized interfaces implemented by this contract. */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceSignature_ERC721Enumerable) || (_interfaceID == InterfaceSignature_ERC721Metadata)); } function implementsERC721() public pure returns (bool) { return true; } } contract CCNFTFactory is ERC721Token, OperationalControl { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new asset comes into existence. event AssetCreated(address owner, uint256 assetId, uint256 assetType, uint256 sequenceId, uint256 creationTime); event DetachRequest(address owner, uint256 assetId, uint256 timestamp); event NFTDetached(address requester, uint256 assetId); event NFTAttached(address requester, uint256 assetId); // Mapping from assetId to uint encoded data for NFT mapping(uint256 => uint256) internal nftDataA; mapping(uint256 => uint128) internal nftDataB; // Mapping from Asset Types to count of that type in exsistance mapping(uint32 => uint64) internal assetTypeTotalCount; mapping(uint32 => uint64) internal assetTypeBurnedCount; // Mapping from index of a Asset Type to get AssetID mapping(uint256 => mapping(uint32 => uint64) ) internal sequenceIDToTypeForID; // Mapping from Asset Type to string name of type mapping(uint256 => string) internal assetTypeName; // Mapping from assetType to creation limit mapping(uint256 => uint32) internal assetTypeCreationLimit; // Indicates if attached system is Active (Transfers will be blocked if attached and active) bool public attachedSystemActive; // Is Asset Burning Active bool public canBurn; // Time LS Oracle has to respond to detach requests uint32 public detachmentTime = 300; /** * @dev Constructor function */ constructor() public { require(msg.sender != address(0)); paused = true; error = false; canBurn = false; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; name_ = "CCNFTFactory"; symbol_ = "CCNFT"; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { uint256 isAttached = getIsNFTAttached(_tokenId); if(isAttached == 2) { //One-Time Auth for Physical Card Transfers require(msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); updateIsAttached(_tokenId, 1); } else if(attachedSystemActive == true && isAttached >= 1) { require(msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); } else { require(isApprovedOrOwner(msg.sender, _tokenId)); } _; } /** Public Functions */ // Returns the AssetID for the Nth assetID for a specific type function getAssetIDForTypeSequenceID(uint256 _seqId, uint256 _type) public view returns (uint256 _assetID) { return sequenceIDToTypeForID[_seqId][uint32(_type)]; } function getAssetDetails(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner ) { require(exists(_assetId)); uint256 nftData = nftDataA[_assetId]; uint256 nftDataBLocal = nftDataB[_assetId]; assetId = _assetId; ownersIndex = ownedTokensIndex[_assetId]; createdTimestamp = uint256(uint48(nftData>>160)); assetType = uint256(uint32(nftData>>208)); assetTypeSeqId = uint256(uint64(nftDataBLocal)); isAttached = uint256(uint48(nftDataBLocal>>64)); creator = address(nftData); owner = ownerOf(_assetId); } function totalSupplyOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeTotalCount[uint32(_type)] - assetTypeBurnedCount[uint32(_type)]; } function totalCreatedOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeTotalCount[uint32(_type)]; } function totalBurnedOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeBurnedCount[uint32(_type)]; } function getAssetRawMeta(uint256 _assetId) public view returns( uint256 dataA, uint128 dataB ) { require(exists(_assetId)); dataA = nftDataA[_assetId]; dataB = nftDataB[_assetId]; } function getAssetIdItemType(uint256 _assetId) public view returns( uint256 assetType ) { require(exists(_assetId)); uint256 dataA = nftDataA[_assetId]; assetType = uint256(uint32(dataA>>208)); } function getAssetIdTypeSequenceId(uint256 _assetId) public view returns( uint256 assetTypeSequenceId ) { require(exists(_assetId)); uint256 dataB = nftDataB[_assetId]; assetTypeSequenceId = uint256(uint64(dataB)); } function getIsNFTAttached( uint256 _assetId) public view returns( uint256 isAttached ) { uint256 nftData = nftDataB[_assetId]; isAttached = uint256(uint48(nftData>>64)); } function getAssetIdCreator(uint256 _assetId) public view returns( address creator ) { require(exists(_assetId)); uint256 dataA = nftDataA[_assetId]; creator = address(dataA); } function isAssetIdOwnerOrApproved(address requesterAddress, uint256 _assetId) public view returns( bool ) { return isApprovedOrOwner(requesterAddress, _assetId); } function getAssetIdOwner(uint256 _assetId) public view returns( address owner ) { require(exists(_assetId)); owner = ownerOf(_assetId); } function getAssetIdOwnerIndex(uint256 _assetId) public view returns( uint256 ownerIndex ) { require(exists(_assetId)); ownerIndex = ownedTokensIndex[_assetId]; } /// @param _owner The owner whose ships tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire NFT owners array looking for NFT belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; // We count on the fact that all Asset have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _itemIndex; for (_itemIndex = 0; _itemIndex < tokenCount; _itemIndex++) { result[resultIndex] = tokenOfOwnerByIndex(_owner,_itemIndex); resultIndex++; } return result; } } // Get the name of the Asset type function getTypeName (uint32 _type) public returns(string) { return assetTypeName[_type]; } /** * @dev Transfers the ownership of a given token ID to another address, modified to prevent transfer if attached and system is active */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } function multiBatchTransferFrom( uint256[] _assetIds, address[] _fromB, address[] _toB) public { uint256 _id; address _to; address _from; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; _to = _toB[i]; _from = _fromB[i]; require(isApprovedOrOwner(msg.sender, _id)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _id); removeTokenFrom(_from, _id); addTokenTo(_to, _id); emit Transfer(_from, _to, _id); } } function batchTransferFrom(uint256[] _assetIds, address _from, address _to) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; require(isApprovedOrOwner(msg.sender, _id)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _id); removeTokenFrom(_from, _id); addTokenTo(_to, _id); emit Transfer(_from, _to, _id); } } function multiBatchSafeTransferFrom( uint256[] _assetIds, address[] _fromB, address[] _toB ) public { uint256 _id; address _to; address _from; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; _to = _toB[i]; _from = _fromB[i]; safeTransferFrom(_from, _to, _id); } } function batchSafeTransferFrom( uint256[] _assetIds, address _from, address _to ) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; safeTransferFrom(_from, _to, _id); } } function batchApprove( uint256[] _assetIds, address _spender ) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; approve(_spender, _id); } } function batchSetApprovalForAll( address[] _spenders, bool _approved ) public { address _spender; for (uint256 i = 0; i < _spenders.length; ++i) { _spender = _spenders[i]; setApprovalForAll(_spender, _approved); } } function requestDetachment( uint256 _tokenId ) public { //Request can only be made by owner or approved address require(isApprovedOrOwner(msg.sender, _tokenId)); uint256 isAttached = getIsNFTAttached(_tokenId); require(isAttached >= 1); if(attachedSystemActive == true) { //Checks to see if request was made and if time elapsed if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) { isAttached = 0; } else if(isAttached > 1) { //Fail if time is already set for attachment require(isAttached == 1); } else { //Is attached, set detachment time and make request to detach emit DetachRequest(msg.sender, _tokenId, block.timestamp); isAttached = block.timestamp; } } else { isAttached = 0; } if(isAttached == 0) { emit NFTDetached(msg.sender, _tokenId); } updateIsAttached(_tokenId, isAttached); } function attachAsset( uint256 _tokenId ) public canTransfer(_tokenId) { uint256 isAttached = getIsNFTAttached(_tokenId); require(isAttached == 0); isAttached = 1; updateIsAttached(_tokenId, isAttached); emit NFTAttached(msg.sender, _tokenId); } function batchAttachAssets(uint256[] _ids) public { for(uint i = 0; i < _ids.length; i++) { attachAsset(_ids[i]); } } function batchDetachAssets(uint256[] _ids) public { for(uint i = 0; i < _ids.length; i++) { requestDetachment(_ids[i]); } } function requestDetachmentOnPause (uint256 _tokenId) public whenPaused { //Request can only be made by owner or approved address require(isApprovedOrOwner(msg.sender, _tokenId)); updateIsAttached(_tokenId, 0); } function batchBurnAssets(uint256[] _assetIDs) public { uint256 _id; for(uint i = 0; i < _assetIDs.length; i++) { _id = _assetIDs[i]; burnAsset(_id); } } function burnAsset(uint256 _assetID) public { // Is Burn Enabled require(canBurn == true); // Deny Action if Attached require(getIsNFTAttached(_assetID) == 0); require(isApprovedOrOwner(msg.sender, _assetID) == true); //Updates Type Total Count uint256 _assetType = getAssetIdItemType(_assetID); assetTypeBurnedCount[uint32(_assetType)] += 1; _burn(msg.sender, _assetID); } /** Dev Functions */ function setTokenURIBase (string _tokenURI) public onlyManager { _setTokenURIBase(_tokenURI); } function setPermanentLimitForType (uint32 _type, uint256 _limit) public onlyManager { //Only allows Limit to be set once require(assetTypeCreationLimit[_type] == 0); assetTypeCreationLimit[_type] = uint32(_limit); } function setTypeName (uint32 _type, string _name) public anyOperator { assetTypeName[_type] = _name; } // Minting Function function batchSpawnAsset(address _to, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator { uint256 _id; uint256 _assetType; for(uint i = 0; i < _assetIds.length; i++) { _id = _assetIds[i]; _assetType = _assetTypes[i]; _createAsset(_to, _assetType, _id, _isAttached, address(0)); } } function batchSpawnAsset(address[] _toB, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator { address _to; uint256 _id; uint256 _assetType; for(uint i = 0; i < _assetIds.length; i++) { _to = _toB[i]; _id = _assetIds[i]; _assetType = _assetTypes[i]; _createAsset(_to, _assetType, _id, _isAttached, address(0)); } } function batchSpawnAssetWithCreator(address[] _toB, uint256[] _assetTypes, uint256[] _assetIds, uint256[] _isAttacheds, address[] _creators) public anyOperator { address _to; address _creator; uint256 _id; uint256 _assetType; uint256 _isAttached; for(uint i = 0; i < _assetIds.length; i++) { _to = _toB[i]; _id = _assetIds[i]; _assetType = _assetTypes[i]; _creator = _creators[i]; _isAttached = _isAttacheds[i]; _createAsset(_to, _assetType, _id, _isAttached, _creator); } } function spawnAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached) public anyOperator { _createAsset(_to, _assetType, _assetID, _isAttached, address(0)); } function spawnAssetWithCreator(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached, address _creator) public anyOperator { _createAsset(_to, _assetType, _assetID, _isAttached, _creator); } /// @dev Remove all Ether from the contract, shouldn&#39;t have any but just incase. function withdrawBalance() public onlyBanker { // We are using this boolean method to make sure that even if one fails it will still work bankManager.transfer(address(this).balance); } // Burn Functions function setCanBurn(bool _state) public onlyManager { canBurn = _state; } function burnAssetOperator(uint256 _assetID) public anyOperator { require(getIsNFTAttached(_assetID) > 0); //Updates Type Total Count uint256 _assetType = getAssetIdItemType(_assetID); assetTypeBurnedCount[uint32(_assetType)] += 1; _burn(ownerOf(_assetID), _assetID); } function toggleAttachedEnforement (bool _state) public onlyManager { attachedSystemActive = _state; } function setDetachmentTime (uint256 _time) public onlyManager { //Detactment Time can not be set greater than 2 weeks. require(_time <= 1209600); detachmentTime = uint32(_time); } function setNFTDetached(uint256 _assetID) public anyOperator { require(getIsNFTAttached(_assetID) > 0); updateIsAttached(_assetID, 0); emit NFTDetached(msg.sender, _assetID); } function setBatchDetachCollectibles(uint256[] _assetIds) public anyOperator { uint256 _id; for(uint i = 0; i < _assetIds.length; i++) { _id = _assetIds[i]; setNFTDetached(_id); } } /** Internal Functions */ // @dev For creating NFT Collectible function _createAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _attachState, address _creator) internal returns(uint256) { uint256 _sequenceId = uint256(assetTypeTotalCount[uint32(_assetType)]) + 1; //Will not allow creation if over limit require(assetTypeCreationLimit[uint32(_assetType)] == 0 || assetTypeCreationLimit[uint32(_assetType)] > _sequenceId); // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. require(_sequenceId == uint256(uint64(_sequenceId))); //Creates NFT _mint(_to, _assetID); uint256 nftData = uint256(_creator); // 160 bit address of creator nftData |= now<<160; // 48 bit creation timestamp nftData |= _assetType<<208; // 32 bit item type uint256 nftDataContinued = uint256(_sequenceId); // 64 bit sequence id of item nftDataContinued |= _attachState<<64; // 48 bit state and/or timestamp for detachment nftDataA[_assetID] = nftData; nftDataB[_assetID] = uint128(nftDataContinued); assetTypeTotalCount[uint32(_assetType)] += 1; sequenceIDToTypeForID[_sequenceId][uint32(_assetType)] = uint64(_assetID); // emit Created event emit AssetCreated(_to, _assetID, _assetType, _sequenceId, now); return _assetID; } function updateIsAttached(uint256 _assetID, uint256 _isAttached) internal { uint256 nftData = nftDataB[_assetID]; uint256 assetTypeSeqId = uint256(uint64(nftData)); uint256 nftDataContinued = uint256(assetTypeSeqId); // 64 bit sequence id of item nftDataContinued |= _isAttached<<64; // 48 bit state and/or timestamp for detachment nftDataB[_assetID] = uint128(nftDataContinued); } }
Internal function to mint a new token Reverts if the given token ID already exists _to address the beneficiary that will own the minted token _tokenId uint256 ID of the token to be minted by the msg.sender/
function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); }
2,379,354
pragma solidity 0.5.16; import "./math/SafeMath.sol"; import "./token/ERC20/ERC20Burnable.sol"; import "./ownership/Ownable.sol"; import "./utils/StringUtils.sol"; /** * @title Premium Item Token * @dev Inherit from it to add ability for your token to sell premium items */ contract PremiumItemToken is ERC20Burnable, Ownable { using SafeMath for uint256; struct PremiumItem { uint256 itemId; uint256 itemPrice; // You can add your own parameters here } event AddPremiumItemEvent(uint256 _itemId); event EditPremiumItemEvent(uint256 _itemId); event DeletePremiumItemEvent(uint256 _itemId); // If we have a record here, then user with address owns item with itemId mapping(address => uint256) private premiumItemOwners; // Database of all available items mapping(uint256 => PremiumItem) private premiumItems; /** * @dev Add new premium item * @param _itemId Id of the new item * @param _itemPrice Price of the new item */ function addPremiumItem(uint256 _itemId, uint256 _itemPrice) external onlyOwner { PremiumItem memory premiumItem = PremiumItem(_itemId, _itemPrice); premiumItems[_itemId] = premiumItem; emit AddPremiumItemEvent(_itemId); } /** * @dev Add new premium items in batch * @param _itemIds Ids of the new items * @param _itemPrices Prices of the new items */ function batchAddPremiumItems(uint256[] calldata _itemIds, uint256[] calldata _itemPrices) external onlyOwner { require(_itemIds.length == _itemPrices.length); for (uint i=0; i<_itemIds.length; i++) { PremiumItem memory premiumItem = PremiumItem(_itemIds[i], _itemPrices[i]); premiumItems[_itemIds[i]] = premiumItem; emit AddPremiumItemEvent(_itemIds[i]); } } /** * @dev Edit premium item * @param _itemId Id of the existing item * @param _itemPrice Price of the existing item to change */ function editPremiumItem(uint256 _itemId, uint256 _itemPrice) external onlyOwner { PremiumItem memory premiumItem = PremiumItem(_itemId, _itemPrice); premiumItems[_itemId] = premiumItem; emit EditPremiumItemEvent(_itemId); } /** * @dev Edit new premium items in batch * @param _itemIds Ids of the existing items * @param _itemPrices Prices of the existing items to change */ function batchEditPremiumItems(uint256[] calldata _itemIds, uint256[] calldata _itemPrices) external onlyOwner { require(_itemIds.length == _itemPrices.length); for (uint i=0; i<_itemIds.length; i++) { PremiumItem memory premiumItem = PremiumItem(_itemIds[i], _itemPrices[i]); premiumItems[_itemIds[i]] = premiumItem; emit EditPremiumItemEvent(_itemIds[i]); } } /** * @dev Delete existing premium item * @param _itemId Id of the item, which should be deleted */ function deletePremiumItem(uint256 _itemId) external onlyOwner { delete premiumItems[_itemId]; emit DeletePremiumItemEvent(_itemId); } /** * @dev Delete existing premium items in batch * @param _itemIds Ids of the items, which should be deleted */ function batchDeletePremiumItems(uint256[] calldata _itemIds) external onlyOwner { for (uint i=0; i<_itemIds.length; i++) { delete premiumItems[_itemIds[i]]; emit DeletePremiumItemEvent(_itemIds[i]); } } /** * @dev Get the price of existing premium item * @param _itemId Id of the existing item * @return Price of the existing item */ function getPremiumItemPrice(uint256 _itemId) public view returns (uint256) { return premiumItems[_itemId].itemPrice; } /** * @dev Buy premium item with selected Id * @param _itemId Id of the item, which user wants to buy */ function buyPremiumItem(uint256 _itemId) external { // We should have such premium item require(premiumItems[_itemId].itemId != 0); // User should have sufficient amount of tokens require(balanceOf(msg.sender) >= premiumItems[_itemId].itemPrice, "Error: insufficient funds"); // User should not posess this item require(!checkPremiumItem(msg.sender, _itemId), "Error: premium item already owned"); // Burn user tokens burn(premiumItems[_itemId].itemPrice); // Grant item premiumItemOwners[msg.sender] = _itemId; } /** * @dev Grant premium item with selected Id to certain user * @param _user Wallet address of the user * @param _itemId Id of the item, which admin wants to grant */ function grantPremiumItem(address _user, uint256 _itemId) external onlyOwner { // We should have such premium item require(premiumItems[_itemId].itemId != 0); // Grant item premiumItemOwners[_user] = _itemId; } /** * @dev Check premium item * @param _user Wallet address of the user * @param _itemId Id of the existing item * @return true if user have such item or false if not */ function checkPremiumItem(address _user, uint256 _itemId) public view returns (bool) { return premiumItemOwners[_user] == _itemId; } }
Buy premium item with selected Id _itemId Id of the item, which user wants to buy/ We should have such premium item User should have sufficient amount of tokens User should not posess this item Burn user tokens Grant item
function buyPremiumItem(uint256 _itemId) external { require(premiumItems[_itemId].itemId != 0); require(balanceOf(msg.sender) >= premiumItems[_itemId].itemPrice, "Error: insufficient funds"); require(!checkPremiumItem(msg.sender, _itemId), "Error: premium item already owned"); burn(premiumItems[_itemId].itemPrice); premiumItemOwners[msg.sender] = _itemId; }
12,767,872
./full_match/43114/0x1db69e08e497639177C11e79d146f24C60FbDe60/sources/https_/github.com/traderjoe-xyz/joe-core/blob/main/contracts/traderjoe/JoeRouter02.sol
refund dust eth, if any
function swapAVAXForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WAVAX, "JoeRouter: INVALID_PATH"); amounts = JoeLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, "JoeRouter: EXCESSIVE_INPUT_AMOUNT"); assert(IWAVAX(WAVAX).transfer(JoeLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); if (msg.value > amounts[0]) TransferHelper.safeTransferAVAX(msg.sender, msg.value - amounts[0]); }
4,643,707
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol
Retrieves the last up-to-date value for the cToken lending balance in terms of its underlying reserve token. _ctoken The Compound cToken address. return _amount The lending balance in terms of the underlying reserve token./
function _fetchLendAmount(address _ctoken) internal returns (uint256 _amount) { return CToken(_ctoken).balanceOfUnderlying(address(this)); }
2,651,031
pragma solidity >= 0.4.22 < 0.6.0; library SafeMath { 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; } 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; } 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 c) { c = a + b; assert(c >= a); return c; } } contract Token { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) balances; mapping(address => bool) public frozenAccount; uint256 totalSupply_; mapping (address => mapping (address => uint256)) internal allowed; function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= balances[_from], "Not enough balance"); //require(_value <= allowed[_from][msg.sender]); //require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); //allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner,address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } 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; } 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; } } contract Stablecoin is Token { string public name = 'Mundo Gold Tethered'; string public symbol = 'MGT'; uint256 public decimals = 4; address payable public owner; uint256 public totalSupplyLimit_; event BuyToken(address from, address to, uint256 value); event SellToken(address from, address to , uint256 value); event Minted(address to, uint256 value); event Burn(address burner, uint256 value); event FrozenFunds(address target, bool frozen); modifier onlyOwner { require(msg.sender == owner); _; } constructor (//uint256 _STOEndTime ) public Token() { //require(_STOEndTime > 0); totalSupplyLimit_ = 2500000000000; owner = msg.sender; mint(owner, totalSupplyLimit_); } function mint(address _to, uint256 _value) public returns (bool) { if (totalSupplyLimit_ >= totalSupply_ + _value) { balances[_to] = balances[_to].add(_value); totalSupply_ = totalSupply_.add(_value); emit Minted(_to, _value); return true; } return false; } /* If the transfer request comes from the STO, it only checks that the investor is in the whitelist * If the transfer request comes from a token holder, it checks that: * a) Both are on the whitelist * b) Seller's sale lockup period is over * c) Buyer's purchase lockup is over */ function verifyTransfer(uint256 _value) public pure returns (bool) { require(_value >= 0); return true; } function burnTokens(address _investor, uint256 _value) public { balances[_investor] = balances[_investor].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(owner, _value); } function buyTokens(address _investor, uint256 _amount) public { //require(_investor != address(0)); //require(_amount > 0); emit BuyToken(owner, _investor, _amount); transferFrom(owner, _investor, _amount); } function sellTokens(address _investor, uint256 _amount) public { //require(_investor != address(0)); //require(_amount > 0); emit SellToken(_investor, owner, _amount); //transferFrom(_investor, owner, _amount); burnTokens(_investor, _amount); } /// @notice Override the functions to not allow token transfers until the end function transfer(address _to, uint256 _value) public returns(bool) { //require(verifyTransfer( owner, _to, _value )); require(!frozenAccount[msg.sender]); // Check if sender is frozen return super.transfer(_to, _value); } /// @notice Override the functions to not allow token transfers until the end function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); // Check if sender is frozen //require(verifyTransfer(_from, _to, _value)); return super.transferFrom(_from, _to, _value); } /// @notice Override the functions to not allow token transfers until the end function approve(address _spender, uint256 _value) public returns(bool) { return super.approve(_spender, _value); } /// @notice Override the functions to not allow token transfers until the end function increaseApproval(address _spender, uint _addedValue) public returns(bool success) { return super.increaseApproval(_spender, _addedValue); } /// @notice Override the functions to not allow token transfers until the end function decreaseApproval(address _spender, uint _subtractedValue) public returns(bool success) { return super.decreaseApproval(_spender, _subtractedValue); } function emergencyExtract() external onlyOwner { owner.transfer(address(this).balance); } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function kill() onlyOwner() public{ selfdestruct(msg.sender); } }
Override the functions to not allow token transfers until the endrequire(verifyTransfer( owner, _to, _value ));
function transfer(address _to, uint256 _value) public returns(bool) { return super.transfer(_to, _value); }
2,502,691
./full_match/1/0x84EAD142210751ACD9eA65A700d98c6c3Ad8b0D9/sources/contracts/FrontRunExample.sol
Contract should only send balance if user knows the secret
function take(string calldata _secret) external { if (keccak256(abi.encodePacked(_secret)) == secretHash) { uint256 _myBalance = address(this).balance; payable(msg.sender).transfer(_myBalance); emit success(); emit fail(); } }
17,038,487
./partial_match/80001/0x129DDF2b913464608EE14f810243949B71F9626E/sources/contracts/data/WitnetBoardData.sol
Gets the Witnet.Result part of a given query.
function __response(uint256 _queryId) internal view returns (Witnet.Response storage) { return __storage().queries[_queryId].response; }
8,816,332
./full_match/56/0xd2C7DD3946bC10f09c56f45eFa68ce8467fedd02/sources/project_/contracts/Tiers.sol
set address of Liquidity locker contract/
function setLiqLockerContract(address _liqContract) external onlyOwner { liquidityLocker = IDCBLiqLocker(_liqContract); emit LiquidityLockerSet(_liqContract); }
3,240,192
./partial_match/1/0x46c89c105e942D6Bcc84672971879ED6994890B9/sources/Snoo.sol
Create a uniswap pair for this new token exclude from paying fees or having max transaction amount
constructor() ERC20("Snoo The Reddit Mascot", "Snoo") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(devWallet, true); internal function that is only called here, and CANNOT be called ever again _createTotalSupply(owner(), 21000000 * (10**18));
15,742,226
./full_match/1/0x702e85f0e100e312bE0D02170F4dDC151361a47b/sources/contracts/protocol/vault/ethereum/ConvexVault/ConvexCurveLPVault.sol
Get current total incentive amount return The total amount of incentive token/
function getCurrentTotalIncentiveAmount() external view override returns (uint256) { if (_incentiveRatio != 0) { address baseRewardPool = getBaseRewardPool(); uint256 earned = IConvexBaseRewardPool(baseRewardPool).earned(address(this)); return earned.percentMul(_incentiveRatio); } return 0; }
3,087,808
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @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. */ 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); _; } } /* * @title ENC ECO System, build in Heco Network * @dev A financial system built on smart contract technology. Open to all, transparent to all. * The worlds first decentralized, community support fund */ contract EncEcosystem is Ownable { IERC20 public invest1ccToken; IERC20 public investEncToken; using SafeMath for uint256; struct PlayerDeposit { uint256 id; uint256 amount; uint256 total_withdraw; uint256 time; uint256 period; uint256 month; uint256 expire; uint8 status; uint8 is_crowd; } struct Player { address referral; uint8 is_supernode; uint256 level_id; uint256 dividends; uint256 referral_bonus; uint256 match_bonus; uint256 supernode_bonus; uint256 total_invested; uint256 total_redeem; uint256 total_withdrawn; uint256 last_payout; PlayerDeposit[] deposits; address[] referrals; } struct PlayerTotal { uint256 total_match_invested; uint256 total_dividends; uint256 total_referral_bonus; uint256 total_match_bonus; uint256 total_supernode_bonus; uint256 total_period1_invested; uint256 total_period2_invested; uint256 total_period3_invested; uint256 total_period4_invested; uint256 total_period1_devidends; uint256 total_period2_devidends; uint256 total_period3_devidends; uint256 total_period4_devidends; } /* Deposit smart contract address */ address public invest_1cc_token_address = 0xFAd7161C74c809C213D88DAc021600D74F6c961c; uint256 public invest_1cc_token_decimal = 4; address public invest_enc_token_address = 0x73724d56fE952bf2eD130A6fb31C1f58dDEdac68; uint256 public invest_enc_token_decimal = 8; /* Platform bonus address */ address public platform_bonus_address = 0x6Fc447828B90d7D7f6C84d5fa688FF3E4ED3763C; /* Platform bonus rate percent(%) */ uint256 constant public platform_bonus_rate = 3; uint256 public total_investors; uint256 public total_invested; uint256 public total_withdrawn; uint256 public total_redeem; uint256 public total_dividends; uint256 public total_referral_bonus; uint256 public total_match_bonus; uint256 public total_supernode_bonus; uint256 public total_platform_bonus; /* Current joined supernode count */ uint256 public total_supernode_num; /* Total supernode join limit number */ uint256 constant public SUPERNODE_LIMIT_NUM = 100; uint256[] public supernode_period_ids = [1, 2, 3]; //period months uint256[] public supernode_period_amounts = [5000,6000,7000]; //period amount uint256[] public supernode_period_limits = [20, 30, 50]; //period limit //supernode total numer in which period uint256[] public total_supernode_num_periods = [0,0,0]; /* Super Node bonus rate */ uint256 constant public supernode_bonus_rate = 30; /* Referral bonuses data define*/ uint8[] public referral_bonuses = [6,4,2,1,1,1,1,1,1,1]; /* Invest period and profit parameter definition */ uint256 constant public invest_early_redeem_feerate = 15; //invest early redeem fee rate(%) uint256[] public invest_period_ids = [1, 2, 3, 4]; //period ids uint256[] public invest_period_months = [3, 6, 12, 24]; //period months uint256[] public invest_period_rates = [600, 700, 800, 900]; //Ten thousand of month' rate uint256[] public invest_period_totals = [0, 0, 0, 0]; //period total invested uint256[] public invest_period_devidends = [0, 0, 0, 0]; //period total devidends /* withdraw fee amount (0.8 1CC)) */ uint256 constant public withdraw_fee_amount = 8000; /* yield reduce project section config, item1: total yield, item2: reduce rate */ uint256[] public yield_reduce_section1 = [30000, 30]; uint256[] public yield_reduce_section2 = [60000, 30]; uint256[] public yield_reduce_section3 = [90000, 30]; uint256[] public yield_reduce_section4 = [290000, 30]; uint256[] public yield_reduce_section5 = [800000, 30]; /* Team level data definition */ uint256[] public team_level_ids = [1,2,3,4,5,6]; uint256[] public team_level_amounts = [1000,3000,5000,10000,20000,50000]; uint256[] public team_level_bonuses = [2,4,6,8,10,12]; /* Crowd period data definition */ uint256[] public crowd_period_ids = [1,2,3]; uint256[] public crowd_period_rates = [4,5,6]; uint256[] public crowd_period_limits = [50000,30000,20000]; /* Total (period) crowd number*/ uint256[] public total_crowd_num_periods = [0,0,0]; /* user invest min amount */ uint256 constant public INVEST_MIN_AMOUNT = 10000000; /* user invest max amount */ uint256 constant public INVEST_MAX_AMOUNT = 100000000000000; /* user crowd limit amount */ uint256 constant public SUPERNODE_LIMIT_AMOUNT = 5000; /* user crowd period(month) */ uint256 constant public crowd_period_month = 24; uint256 constant public crowd_period_start = 1634313600; /* Mapping data list define */ mapping(address => Player) public players; mapping(address => PlayerTotal) public playerTotals; mapping(uint256 => address) public addrmap; address[] public supernodes; event Deposit(address indexed addr, uint256 amount, uint256 month); event Withdraw(address indexed addr, uint256 amount); event Crowd(address indexed addr, uint256 period,uint256 amount); event SuperNode(address indexed addr, uint256 _period, uint256 amount); event DepositRedeem(uint256 invest_id); event ReferralPayout(address indexed addr, uint256 amount, uint8 level); event SetReferral(address indexed addr,address refferal); constructor() public { /* Create invest token instace */ invest1ccToken = IERC20(invest_1cc_token_address); investEncToken = IERC20(invest_enc_token_address); } /* Function to receive Ether. msg.data must be empty */ receive() external payable {} /* Fallback function is called when msg.data is not empty */ fallback() external payable {} function getBalance() public view returns (uint) { return address(this).balance; } /* * @dev user do set refferal action */ function setReferral(address _referral) payable external { Player storage player = players[msg.sender]; require(player.referral == address(0), "Referral has been set"); require(_referral != address(0), "Invalid Referral address"); Player storage ref_player = players[_referral]; require(ref_player.referral != address(0) || _referral == platform_bonus_address, "Referral address not activated yet"); _setReferral(msg.sender,_referral); emit SetReferral(msg.sender,_referral); } /* * @dev user do join shareholder action, to join SUPERNODE */ function superNode(address _referral, uint256 _period, uint256 _amount) payable external { Player storage player = players[msg.sender]; require(player.is_supernode == 0, "Already a supernode"); require(_period >= 1 && _period <= 3 , "Invalid Period Id"); if(_period > 1){ uint256 _lastPeriodLimit = supernode_period_limits[_period-2]; require(total_supernode_num_periods[_period-2] >= _lastPeriodLimit, "Current round not started yet "); } uint256 _periodAmount = supernode_period_amounts[_period-1]; require(_amount == _periodAmount, "Not match the current round limit"); //valid period remain uint256 _periodRemain = supernode_period_limits[_period-1] - total_supernode_num_periods[_period-1]; require(_periodRemain > 0, "Out of current period limit"); /* format token amount */ uint256 token_amount = _getTokenAmount(_amount,invest_1cc_token_decimal); /* Transfer user address token to contract address*/ require(invest1ccToken.transferFrom(msg.sender, address(this), token_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* set the player of supernodes roles */ player.is_supernode = 1; total_supernode_num += 1; total_supernode_num_periods[_period-1] += 1; /* push user to shareholder list*/ supernodes.push(msg.sender); emit SuperNode(msg.sender, _period, _amount); } /* * @dev user do crowd action, to get enc */ function crowd(address _referral, uint256 _period, uint256 _amount) payable external { require(_period >= 1 && _period <= 3 , "Invalid Period Id"); if(_period > 1){ uint256 _lastPeriodLimit = crowd_period_limits[_period-2]; require(total_crowd_num_periods[_period-2] >= _lastPeriodLimit, "Current round not started yet "); } //valid period remain uint256 _periodRemain = crowd_period_limits[_period-1] - total_crowd_num_periods[_period-1]; require(_periodRemain > 0, "Out of current period limit"); uint256 _periodRate = crowd_period_rates[_period-1]; uint256 token_enc_amount = _getTokenAmount(_amount,invest_enc_token_decimal); uint256 token_1cc_amount = _getTokenAmount(_amount.mul(_periodRate),invest_1cc_token_decimal); /* Transfer user address token to contract address*/ require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* get the period total time (total secones) */ uint256 _period_ = 4; uint256 _month = crowd_period_month; uint256 period_time = _month.mul(30).mul(86400); //updater period total number total_crowd_num_periods[_period-1] += _amount; Player storage player = players[msg.sender]; /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: token_enc_amount, total_withdraw: 0, time: uint256(block.timestamp), period: _period_, month: _month, expire: uint256(block.timestamp).add(period_time), status: 0, is_crowd: 1 })); //update total invested player.total_invested += token_enc_amount; total_invested += token_enc_amount; invest_period_totals[_period_-1] += token_enc_amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period_, token_enc_amount, 1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, token_enc_amount, 1); emit Crowd(msg.sender, _period, _amount); } /* * @dev user do deposit action,grant the referrs bonus,grant the shareholder bonus,grant the match bonus */ function deposit(address _referral, uint256 _amount, uint256 _period) external payable { require(_period >= 1 && _period <= 4 , "Invalid Period Id"); uint256 _month = invest_period_months[_period-1]; /* format token amount */ uint256 _decimal = invest_enc_token_decimal - invest_1cc_token_decimal; uint256 token_enc_amount = _amount; uint256 token_1cc_amount = _amount.div(10**_decimal); require(token_enc_amount >= INVEST_MIN_AMOUNT, "Minimal deposit: 0.1 enc"); require(token_enc_amount <= INVEST_MAX_AMOUNT, "Maxinum deposit: 1000000 enc"); Player storage player = players[msg.sender]; require(player.deposits.length < 2000, "Max 2000 deposits per address"); /* Transfer user address token to contract address*/ require(investEncToken.transferFrom(msg.sender, address(this), token_enc_amount), "transferFrom failed"); require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } /* get the period total time (total secones) */ uint256 period_time = _month.mul(30).mul(86400); uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: token_enc_amount, total_withdraw: 0, time: uint256(block.timestamp), period: _period, month: _month, expire:uint256(block.timestamp).add(period_time), status: 0, is_crowd: 0 })); player.total_invested += token_enc_amount; total_invested += token_enc_amount; invest_period_totals[_period-1] += token_enc_amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period, token_enc_amount, 1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, token_enc_amount, 1); emit Deposit(msg.sender, _amount, _month); } /* * @dev user do withdraw action, tranfer the total profit to user account, grant rereferral bonus, grant match bonus, grant shareholder bonus */ function withdraw() payable external { /* update user dividend data */ _payout(msg.sender); Player storage player = players[msg.sender]; uint256 _amount = player.dividends + player.referral_bonus + player.match_bonus + player.supernode_bonus; require(_amount >= 10000000, "Minimal payout: 0.1 ENC"); /* format deposit token amount */ uint256 token_enc_amount = _amount; /* process token transfer action */ require(investEncToken.approve(address(this), token_enc_amount), "approve failed"); require(investEncToken.transferFrom(address(this), msg.sender, token_enc_amount), "transferFrom failed"); /*transfer service fee to contract*/ uint256 token_1cc_fee_amount = withdraw_fee_amount; require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_fee_amount), "transferFrom failed"); uint256 _dividends = player.dividends; /* Update user total payout data */ _updatePlayerTotalPayout(msg.sender, token_enc_amount); /* Grant referral bonus */ _referralPayout(msg.sender, _dividends); /* Grant super node bonus */ _superNodesPayout(_dividends); /* Grant team match bonus*/ _matchPayout(msg.sender, _dividends); emit Withdraw(msg.sender, token_enc_amount); } /* * @dev user do deposit redeem action,transfer the expire deposit's amount to user account */ function depositRedeem(uint256 _invest_id) payable external { Player storage player = players[msg.sender]; require(player.deposits.length >= _invest_id && _invest_id > 0, "Valid deposit id"); uint256 _index = _invest_id - 1; require(player.deposits[_index].status == 0, "Invest is redeemed"); //crowded deposit can't do early redeem action //if(player.deposits[_index].is_crowd == 1) { require(player.deposits[_index].expire < block.timestamp, "Invest not expired"); //} /* formt deposit token amount */ uint256 token_enc_amount = player.deposits[_index].amount; //deposit is not expired, deduct the fee (10%) if(player.deposits[_index].expire > block.timestamp){ //token_enc_amount = token_enc_amount * (100 - invest_early_redeem_feerate) / 100; } /* process token transfer action*/ require(investEncToken.approve(address(this), token_enc_amount), "approve failed"); require(investEncToken.transferFrom(address(this), msg.sender, token_enc_amount), "transferFrom failed"); /* update deposit status in redeem */ player.deposits[_index].status = 1; uint256 _amount = player.deposits[_index].amount; /* update user token balance*/ player.total_invested -= _amount; /* update total invested/redeem amount */ total_invested -= _amount; total_redeem += _amount; /* update invest period total invested amount*/ uint256 _period = player.deposits[_index].period; invest_period_totals[_period-1] -= _amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period, _amount, -1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, -1); emit DepositRedeem(_invest_id); } /* * @dev Update Referral Match invest amount, total investor number, map investor address index */ function _updateReferralMatchInvestedAmount(address _addr,uint256 _amount,int8 _opType) private { if(_opType > 0) { playerTotals[_addr].total_match_invested += _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested += _amount; ref = players[ref].referral; } }else{ playerTotals[_addr].total_match_invested -= _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested -= _amount; ref = players[ref].referral; } } } /* * @dev Update user total payout data */ function _updatePlayerTotalPayout(address _addr,uint256 token_amount) private { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* update user Withdraw total amount*/ player.total_withdrawn += token_amount; playerTotal.total_dividends += player.dividends; playerTotal.total_referral_bonus += player.referral_bonus; playerTotal.total_match_bonus += player.match_bonus; playerTotal.total_supernode_bonus += player.supernode_bonus; /* update platform total data*/ total_withdrawn += token_amount; total_dividends += player.dividends; total_referral_bonus += player.referral_bonus; total_match_bonus += player.match_bonus; total_supernode_bonus += player.supernode_bonus; uint256 _platform_bonus = (token_amount * platform_bonus_rate / 100); total_platform_bonus += _platform_bonus; /* update platform address bonus*/ players[platform_bonus_address].match_bonus += _platform_bonus; /* reset user bonus data */ player.dividends = 0; player.referral_bonus = 0; player.match_bonus = 0; player.supernode_bonus = 0; } /* * @dev get user deposit expire status */ function _getExpireStatus(address _addr) view private returns(uint256 value) { Player storage player = players[_addr]; uint256 _status = 1; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { _status = 0; break; } } return _status; } /* * @dev update user referral data */ function _setReferral(address _addr, address _referral) private { /* if user referral is not set */ if(players[_addr].referral == address(0) && _referral != _addr && _referral != address(0)) { Player storage ref_player = players[_referral]; if(ref_player.referral != address(0) || _referral == platform_bonus_address){ players[_addr].referral = _referral; /* update user referral address list*/ players[_referral].referrals.push(_addr); } } } /* * @dev Grant user referral bonus in user withdraw */ function _referralPayout(address _addr, uint256 _amount) private { address ref = players[_addr].referral; uint256 _day_payout = _payoutOfDay(_addr); if(_day_payout == 0) return; for(uint8 i = 0; i < referral_bonuses.length; i++) { if(ref == address(0)) break; uint256 _ref_day_payout = _payoutOfDay(ref); uint256 _token_amount = _amount; /* user bonus double burn */ if(_ref_day_payout * 2 < _day_payout){ _token_amount = _token_amount * (_ref_day_payout * 2) / _day_payout; } //validate account deposit is all expired or not uint256 _is_expire = _getExpireStatus(ref); if(_is_expire == 0) { uint256 bonus = _token_amount * referral_bonuses[i] / 100; players[ref].referral_bonus += bonus; } ref = players[ref].referral; } } /* * @dev Grant shareholder full node bonus in user withdraw */ function _superNodesPayout(uint256 _amount) private { uint256 _supernode_num = supernodes.length; if(_supernode_num == 0) return; uint256 bonus = _amount * supernode_bonus_rate / 100 / _supernode_num; for(uint256 i = 0; i < _supernode_num; i++) { address _addr = supernodes[i]; players[_addr].supernode_bonus += bonus; } } /* * @dev Grant Match bonus in user withdraw */ function _matchPayout(address _addr,uint256 _amount) private { /* update player team level */ _upgradePlayerTeamLevel(_addr); uint256 last_level_id = players[_addr].level_id; /* player is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) return; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; //validate account deposit is all expired or not uint256 _is_expire = _getExpireStatus(ref); /* upgrade player team level id*/ _upgradePlayerTeamLevel(ref); if(players[ref].level_id > last_level_id){ uint256 last_level_bonus = 0; if(last_level_id > 0){ last_level_bonus = team_level_bonuses[last_level_id-1]; } uint256 cur_level_bonus = team_level_bonuses[players[ref].level_id-1]; uint256 bonus_amount = _amount * (cur_level_bonus - last_level_bonus) / 100; if(_is_expire==0){ players[ref].match_bonus += bonus_amount; } last_level_id = players[ref].level_id; /* referral is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) break; } ref = players[ref].referral; } } /* * @dev upgrade player team level id */ function _upgradePlayerTeamLevel(address _addr) private { /* get community total invested*/ uint256 community_total_invested = _getCommunityTotalInvested(_addr); uint256 level_id = 0; for(uint8 i=0; i < team_level_ids.length; i++){ uint256 _team_level_amount = _getTokenAmount(team_level_amounts[i], invest_enc_token_decimal); if(community_total_invested >= _team_level_amount){ level_id = team_level_ids[i]; } } players[_addr].level_id = level_id; } /* * @dev Get community total invested */ function _getCommunityTotalInvested(address _addr) view private returns(uint256 value) { address[] memory referrals = players[_addr].referrals; uint256 nodes_max_invested = 0; uint256 nodes_total_invested = 0; for(uint256 i=0;i<referrals.length;i++){ address ref = referrals[i]; nodes_total_invested += playerTotals[ref].total_match_invested; if(playerTotals[ref].total_match_invested > nodes_max_invested){ nodes_max_invested = playerTotals[ref].total_match_invested; } } return (nodes_total_invested - nodes_max_invested); } /* * @dev user withdraw, user devidends data update */ function _payout(address _addr) private { uint256 payout = this.payoutOf(_addr); if(payout > 0) { _updateTotalPayout(_addr); players[_addr].last_payout = uint256(block.timestamp); players[_addr].dividends += payout; } } /* * @dev format token amount with token decimal */ function _getTokenAmount(uint256 _amount,uint256 _token_decimal) pure private returns(uint256 token_amount) { uint256 token_decimals = 10 ** _token_decimal; token_amount = _amount * token_decimals; return token_amount; } /* * @dev update user total withdraw data */ function _updateTotalPayout(address _addr) private { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); uint256 _dep_payout = _day_payout * (to - from) / 86400; uint256 _period = player.deposits[i].period; player.deposits[i].total_withdraw += _dep_payout; invest_period_devidends[_period-1]+= _dep_payout; //update player period total devidend data _updatePlayerPeriodTotalDevidendsData(msg.sender,_period,_dep_payout); } } } /* * @dev update player period total invest data */ function _updatePlayerPeriodTotalInvestedData(address _addr,uint256 _period,uint256 _token_amount,int8 _opType) private { if(_opType==-1){ if(_period==1){ playerTotals[_addr].total_period1_invested -= _token_amount; return; } if(_period==2){ playerTotals[_addr].total_period2_invested -= _token_amount; return; } if(_period==3){ playerTotals[_addr].total_period3_invested -= _token_amount; return; } if(_period==4){ playerTotals[_addr].total_period4_invested -= _token_amount; return; } }else{ if(_period==1){ playerTotals[_addr].total_period1_invested += _token_amount; return; } if(_period==2){ playerTotals[_addr].total_period2_invested += _token_amount; return; } if(_period==3){ playerTotals[_addr].total_period3_invested += _token_amount; return; } if(_period==4){ playerTotals[_addr].total_period4_invested += _token_amount; return; } } } /* * @dev update player period total devidend data */ function _updatePlayerPeriodTotalDevidendsData(address _addr,uint256 _period,uint256 _dep_payout) private { if(_period==1){ playerTotals[_addr].total_period1_devidends += _dep_payout; return; } if(_period==2){ playerTotals[_addr].total_period2_devidends += _dep_payout; return; } if(_period==3){ playerTotals[_addr].total_period3_devidends += _dep_payout; return; } if(_period==4){ playerTotals[_addr].total_period4_devidends += _dep_payout; return; } } /* * @dev get the invest period rate, if total yield reached reduce limit, invest day rate will be reduce */ function _getInvestDayPayoutOf(uint256 _amount, uint256 _period) view private returns(uint256 value) { /* get invest period base rate*/ uint256 period_month_rate = invest_period_rates[_period-1]; /* format amount with token decimal */ uint256 token_amount = _amount; value = token_amount * period_month_rate / 30 / 10000; if(value > 0){ /* total yield reached 30,000,start first reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section1[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section1[1]) / 100; } /* total yield reached 60,000,start second reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section2[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section2[1]) / 100; } /* total yield reached 90,000,start third reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section3[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section3[1]) / 100; } /* total yield reached 290,000,start fourth reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section4[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section4[1]) / 100; } /* total yield reached 890,000,start fifth reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section5[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section5[1]) / 100; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function payoutOf(address _addr) view external returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); value += _day_payout * (to - from) / 86400; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function _payoutOfDay(address _addr) view private returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; //uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; //uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount, dep.period); value += _day_payout; } } return value; } /* * @dev Remove supernodes of the special address */ function _removeSuperNodes(address _addr) private { for (uint index = 0; index < supernodes.length; index++) { if(supernodes[index] == _addr){ for (uint i = index; i < supernodes.length-1; i++) { supernodes[i] = supernodes[i+1]; } delete supernodes[supernodes.length-1]; break; } } } /* * @dev get contract data info * @return total invested,total investor number,total withdraw,total referral bonus */ function contractInfo() view external returns( uint256 _total_invested, uint256 _total_investors, uint256 _total_withdrawn, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_platform_bonus, uint256 _total_supernode_num, uint256 _crowd_period_month, uint256 _crowd_period_start, uint256 _total_holder_bonus, uint256 _total_match_bonus) { return ( total_invested, total_investors, total_withdrawn, total_dividends, total_referral_bonus, total_platform_bonus, total_supernode_num, crowd_period_month, crowd_period_start, total_supernode_bonus, total_match_bonus ); } /* * @dev get user info * @return pending withdraw amount,referral,rreferral num etc. */ function userInfo(address _addr) view external returns ( address _referral, uint256 _referral_num, uint256 _is_supernode, uint256 _dividends, uint256 _referral_bonus, uint256 _match_bonus, uint256 _supernode_bonus,uint256 _last_payout ) { Player storage player = players[_addr]; return ( player.referral, player.referrals.length, player.is_supernode, player.dividends, player.referral_bonus, player.match_bonus, player.supernode_bonus, player.last_payout ); } /* * @dev get user info * @return pending withdraw amount,referral bonus, total deposited, total withdrawn etc. */ function userInfoTotals(address _addr) view external returns( uint256 _total_invested, uint256 _total_withdrawn, uint256 _total_community_invested, uint256 _total_match_invested, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_match_bonus, uint256 _total_supernode_bonus ) { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* get community total invested*/ uint256 total_community_invested = _getCommunityTotalInvested(_addr); return ( player.total_invested, player.total_withdrawn, total_community_invested, playerTotal.total_match_invested, playerTotal.total_dividends, playerTotal.total_referral_bonus, playerTotal.total_match_bonus, playerTotal.total_supernode_bonus ); } /* * @dev get user investment list */ function getInvestList(address _addr) view external returns( uint256[] memory ids,uint256[] memory times, uint256[] memory months, uint256[] memory amounts,uint256[] memory withdraws, uint256[] memory statuses,uint256[] memory payouts) { Player storage player = players[_addr]; PlayerDeposit[] memory deposits = _getValidInvestList(_addr); uint256[] memory _ids = new uint256[](deposits.length); uint256[] memory _times = new uint256[](deposits.length); uint256[] memory _months = new uint256[](deposits.length); uint256[] memory _amounts = new uint256[](deposits.length); uint256[] memory _withdraws = new uint256[](deposits.length); uint256[] memory _statuses = new uint256[](deposits.length); uint256[] memory _payouts = new uint256[](deposits.length); for(uint256 i = 0; i < deposits.length; i++) { PlayerDeposit memory dep = deposits[i]; _ids[i] = dep.id; _amounts[i] = dep.amount; _withdraws[i] = dep.total_withdraw; _times[i] = dep.time; _months[i] = dep.month; _statuses[i] = dep.is_crowd; _months[i] = dep.month; //get deposit current payout uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); uint256 _value = _day_payout * (to - from) / 86400; _payouts[i] = _value; } } return ( _ids, _times, _months, _amounts, _withdraws, _statuses, _payouts ); } /* * @dev get deposit valid count */ function _getValidInvestList(address _addr) view private returns(PlayerDeposit[] memory) { Player storage player = players[_addr]; uint256 resultCount; for (uint i = 0; i < player.deposits.length; i++) { if ( player.deposits[i].status == 0) { resultCount++; } } PlayerDeposit[] memory deposits = new PlayerDeposit[](resultCount); uint256 j; for(uint256 i = 0; i < player.deposits.length; i++){ if(player.deposits[i].status==0){ deposits[j] = player.deposits[i]; j++; } } return deposits; } /* * @dev get crowd period list */ function getCrowdPeriodList() view external returns(uint256[] memory ids,uint256[] memory rates, uint256[] memory limits, uint256[] memory totals) { return ( crowd_period_ids, crowd_period_rates, crowd_period_limits, total_crowd_num_periods ); } /* * @dev get invest period list */ function getInvestPeriodList(address _addr) view external returns( uint256[] memory ids,uint256[] memory months, uint256[] memory rates,uint256[] memory totals, uint256[] memory devidends,uint256[] memory user_investeds, uint256[] memory user_devidends) { PlayerTotal storage playerTotal = playerTotals[_addr]; uint256[] memory _user_period_investeds = new uint256[](4); uint256[] memory _user_period_devidends = new uint256[](4); _user_period_investeds[0] = playerTotal.total_period1_invested; _user_period_investeds[1] = playerTotal.total_period2_invested; _user_period_investeds[2] = playerTotal.total_period3_invested; _user_period_investeds[3] = playerTotal.total_period4_invested; _user_period_devidends[0] = playerTotal.total_period1_devidends; _user_period_devidends[1] = playerTotal.total_period2_devidends; _user_period_devidends[2] = playerTotal.total_period3_devidends; _user_period_devidends[3] = playerTotal.total_period4_devidends; return ( invest_period_ids, invest_period_months, invest_period_rates, invest_period_totals, invest_period_devidends, _user_period_investeds, _user_period_devidends ); } /* * @dev get supernode period list */ function getSuperNodePeriodList() view external returns(uint256[] memory ids,uint256[] memory amounts, uint256[] memory limits,uint256[] memory totals) { return ( supernode_period_ids, supernode_period_amounts, supernode_period_limits, total_supernode_num_periods ); } }
Remove supernodes of the special address/
function _removeSuperNodes(address _addr) private { for (uint index = 0; index < supernodes.length; index++) { if(supernodes[index] == _addr){ for (uint i = index; i < supernodes.length-1; i++) { supernodes[i] = supernodes[i+1]; } delete supernodes[supernodes.length-1]; break; } } }
12,749,409
/** *Submitted for verification at Etherscan.io on 2022-03-30 */ /* solhint-disable */ /** **/ //https://t.me/cking_verification // SPDX-License-Identifier: Unlicensed // 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, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // 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, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // 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); } } } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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 ); } // File: contracts/Cryptokinginu.sol pragma solidity ^0.8.10; contract CryptoKingToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) public _isBlackListed; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1 * 10**15 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Crypto King Inu"; string private _symbol = "CKING"; uint8 private _decimals = 9; struct BuyFee { uint16 developmentFee; uint16 taxFee; } struct SellFee { uint16 developmentFee; uint16 taxFee; } BuyFee public buyFee; SellFee public sellFee; uint16 private _taxFee; uint16 private _developmentFee; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public _developmentWallet = payable(address(0x4123)); bool internal inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool private isTradingEnabled; uint256 public tradingStartBlock; uint256 private lastBlock; uint256 public maxBuyAmount; uint256 public maxSellAmount; uint256 public maxWalletAmount; uint256 private swapTokensAtAmount = 1 * 10**9 * 10**9; uint8 public constant BLOCKCOUNT = 2; //Blacklist first 2 block buys event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; buyFee.developmentFee = 7; buyFee.taxFee = 3; sellFee.developmentFee = 12; sellFee.taxFee = 3; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D //Uniswap Router ); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; maxSellAmount = totalSupply().mul(125).div(100000); maxBuyAmount = totalSupply().mul(125).div(100000); maxWalletAmount = totalSupply().mul(5).div(1000); lastBlock = block.number; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } 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; } function enableTrading() external onlyOwner { isTradingEnabled = true; tradingStartBlock = block.number; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function setBlackList(address addr, bool value) external onlyOwner { _isBlackListed[addr] = value; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setBuyFee(uint16 development, uint16 tax) external onlyOwner { buyFee.developmentFee = development; buyFee.taxFee = tax; uint256 totalBuyFee = development + tax; require (totalBuyFee <= 20, "max buy tax limit is 20%"); } function setSellFee( uint16 development, uint16 tax ) external onlyOwner { sellFee.developmentFee = development; sellFee.taxFee = tax; uint256 totalSellFee = development + tax; require (totalSellFee <= 20, "max sell tax limit is 20%"); } function setSwapTokensAtAmount(uint256 numTokens) external onlyOwner { swapTokensAtAmount = numTokens * 10**9; } function updateRouter(address newAddress) external onlyOwner { require( newAddress != address(uniswapV2Router), "TOKEN: The router already has that address" ); uniswapV2Router = IUniswapV2Router02(newAddress); address get_pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair( address(this), uniswapV2Router.WETH() ); if (get_pair == address(0)) { uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); } else { uniswapV2Pair = get_pair; } } function setMaxWallet(uint256 value) external onlyOwner { require(value > 10000000, "No rug Pull"); maxWalletAmount = value * 10**9; } function setMaxBuyAmount(uint256 value) external onlyOwner { require(value > 10000000, "No rug Pull"); maxBuyAmount = value * 10**9; } function setMaxSellAmount(uint256 value) external onlyOwner { require(value > 10000000, "No rug Pull"); maxSellAmount = value * 10**9; } function setDevelopmentWallet(address payable wallet) external onlyOwner { require( wallet != address(0), "developmentWallet address can not be zero!" ); _developmentWallet = wallet; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function claimStuckTokens(address _token) external onlyOwner { require(_token != address(this), "No rug pulls :)"); if (_token == address(0x0)) { payable(owner()).transfer(address(this).balance); return; } IERC20 erc20token = IERC20(_token); uint256 balance = erc20token.balanceOf(address(this)); erc20token.transfer(owner(), balance); } //to recieve ETH from uniswapV2Router when swaping receive() external payable { this; } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tDevelopment ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tDevelopment, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tDevelopment = calculateDevelopmentFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee); tTransferAmount = tTransferAmount.sub(tDevelopment); return (tTransferAmount, tFee, tDevelopment); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tDevelopment, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rDevelopment = tDevelopment.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub( rDevelopment ); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeDevelopment(uint256 tDevelopment) private { uint256 currentRate = _getRate(); uint256 rDevelopment = tDevelopment.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rDevelopment); if (_isExcluded[address(this)]) { _tOwned[address(this)] = _tOwned[address(this)].add(tDevelopment); } } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateDevelopmentFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_developmentFee).div(10**2); } function removeAllFee() private { _taxFee = 0; _developmentFee = 0; } function setBuy() private { _taxFee = buyFee.taxFee; _developmentFee = buyFee.developmentFee; } function setSell() private { _taxFee = sellFee.taxFee; _developmentFee = sellFee.developmentFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require( !_isBlackListed[from] && !_isBlackListed[to], "Account is blacklisted" ); require( isTradingEnabled || _isExcludedFromFee[from], "Trading not enabled yet" ); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; uint256 forDevelopment = contractTokenBalance; if (forDevelopment > 0) { swapAndSendDevelopment(forDevelopment); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } //transfer amount, it will take tax, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndSendDevelopment(uint256 amount) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(amount); uint256 newBalance = address(this).balance.sub(initialBalance); payable(_developmentWallet).transfer(newBalance); } 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 address(0xdead), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { removeAllFee(); if (takeFee) { require(block.number > lastBlock, "One transfer per block"); lastBlock = block.number; if (recipient != uniswapV2Pair) { require( balanceOf(recipient) + amount <= maxWalletAmount, "Balance exceeds limit" ); } if (sender == uniswapV2Pair) { require(amount <= maxBuyAmount, "Buy exceeds limit"); if (block.number < tradingStartBlock + BLOCKCOUNT) { _isBlackListed[recipient] = true; } setBuy(); } if (recipient == uniswapV2Pair) { require(amount <= maxSellAmount, "Sell exceeds limit"); setSell(); } } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeDevelopment(calculateDevelopmentFee(tAmount)); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeDevelopment(calculateDevelopmentFee(tAmount)); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeDevelopment(calculateDevelopmentFee(tAmount)); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeDevelopment(calculateDevelopmentFee(tAmount)); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { removeAllFee(); if (takeFee) { require(block.number > lastBlock, "One transfer per block"); lastBlock = block.number; if (recipient != uniswapV2Pair) { require( balanceOf(recipient) + amount <= maxWalletAmount, "Balance exceeds limit" ); } if (sender == uniswapV2Pair) { require(amount <= maxBuyAmount, "Buy exceeds limit"); if (block.number < tradingStartBlock + BLOCKCOUNT) { _isBlackListed[recipient] = true; } setBuy(); } if (recipient == uniswapV2Pair) { require(amount <= maxSellAmount, "Sell exceeds limit"); setSell(); } } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } }
7,616,350
//COPYRIGHT © THE FORCE PROTOCOL FOUNDATION LTD. //The Force Protocol Stablecoin system - Collateral management //原力协议稳定币系统 - 抵押物管理 pragma solidity >= 0.5.0; import "./Authority.sol"; contract IToken { function transfer(address,uint) public returns (bool); function transferFrom(address,address,uint) public returns (bool); function approve(address who, uint amount) public returns (bool); } contract IFeeder { function get() public view returns (uint256); function valid() public view returns (bool); } contract IDebtor { function mint(address who, uint256 amount) public; function burn(address who, uint256 amount) public; function inci(uint256 amount) public; function deci(uint256 amount) public; function incb(uint256 amount) public; function tok() public view returns(address); function tot() public view returns(uint256); } contract IAsset { function deposit(address who, uint256 amount) public payable; function move(address from, address to, uint256 amount) public; } contract IWallet { function get(address tok) public returns(address); } contract ILiquidauction { function auction(address who, address rve, address oss, uint256 oam, address iss, uint256 iam, uint256 bid) public returns(uint256); } contract IJoined { function join(address who) public returns(uint256); } contract Collateral is Authority { struct hstate { uint256 c; //locked-collateral, 锁定状态的抵押物数量 uint256 s; //stablecoin, 已借出的稳定币数量 uint256 k; //unlocked-collateral, 未锁定状态的抵押物数量 } uint256 public tot; //抵押物产生的稳定币总量(total) mapping (address => hstate) public hol; //以账户为单位记录持有状态(hold state of address) uint256 public rat; //利率(rate) uint256 public rit; //最后rise时间(rise-time), rise 计算一段时间内产生的利息并累计到债务管理器 uint256 public exr; //兑换比率, 基于ove计算(exchange rate) address public tok; IDebtor public dor; //债务管理器(debtor) bool public hea; //系统状态标记(healthy), false 表示系统已经停止运行, 并允许捐助者按比例取回 uint256 public pce; //当前抵押物价格(price); address public wet; //wallet address public jin; //Joined, 记录已经使用过系统的账户. /** 治理参数 */ uint256 public upp; //允许抵押物产生的稳定币总量上限(upper) uint256 public low; //允许抵押物产生的稳定币总量下限(lower) uint256 public ove; //最小抵押率(overflow) uint256 public gth; //利率增长量(growth) uint256 public seg; //单次清算数量(segmentation). uint256 public fin; //清算罚金(fine) address public fer; //喂价器(feeder) address public lau; //清算器账户地址(liquidation auction). event Feed(uint256 val, uint256 exr); event Payback(address indexed who, uint256 s, uint256 c); event Borrow(address indexed who, uint256 c, uint256 s); event Deposit(address indexed sender, address indexed who, uint256 amount); event Withdraw(address indexed sender, address indexed who, uint256 amount); /** 初始化 */ constructor(address w, address t, address d, address l, address j) public { wet = w; tok = t; dor = IDebtor(d); lau = l; jin = j; hea = true; rit = now; rat = PRE; } /** 治理 */ function setupp(uint256 v) public auth { upp = v; } function setlow(uint256 v) public auth { low = v; } function setove(uint256 v) public auth { ove = v; } function setgth(uint256 v) public auth { gth = v; } function setseg(uint256 v) public auth { seg = v; } function setfin(uint256 v) public auth { fin = v; } function setfer(address v) public auth { fer = v; } function setlau(address v) public auth { lau = v; } function sethea(bool v) public auth { hea = v; } /** 喂价 */ function feed() public { pce = IFeeder(fer).get(); //抵押物价格(val): 1 USD //最小抵押率(ove): 150% //兑换比(exr): val/ove = 1/1.5, 表示1.5个抵押物才兑换1个Qian, 或者说1个抵押物大约能兑换 0.6666666666666666... 个 Qian //乘以PRE(10 ** 18)是防止0.6666...被抹成0 exr = (pce * PRE * PRE9) / ove; //[10^27] emit Feed(pce, exr); } /** 抵押/赎回 */ //赎回(稳定币=>抵押物) //调用赎回接口分两种情况: //1. 仅归还稳定币, 仅为用户减少 @snt 的稳定币持有数量(hol[u].s - @snt), 不减少抵押物的数量(@cnt为0, 即 hol[u].e 不变), // 相当于提高了质押率, 但是那些没有稳定币对应的抵押物可以随时取出(从 hol[u].e 转移到 hol[u].c)), // 如果稳定币的持有数量不足以归还系统债务, 则未还的债务必须存在相应数量的的抵押物. //2. 仅取走抵押物, 仅为用户减少 @cnt 的抵押物持有数量(hol[u].e - @cnt), 不减少稳定币的数量(@s为0, 即 hol[u].s 不变). // 相当于降低了质押率, 但剩余的抵押物数量最少要满足未还债务的最小抵押率. // //后续需要区分 @hol[u].e 中有多少是属于稳定币对应的抵押物和多少没有稳定币对应的抵押物, 算法为: //计算稳定币对应的抵押物数量(amount): // hol[u].s * rat = amount * exr; // amount = hol[u].s * rat / exr; // amount = hol[u].s * rat / (price / ove) // amount = hol[u].s * rat * ove / price; //计算没有稳定币对应的抵押物数量: // hol[u].e - amount; function payback(address who, uint256 s, uint256 c) public { address u = who; require(rat != 0, "rate must not be 0"); require(hea, "system has been stopped"); //增加未锁定的抵押物持有记录. hol[u].k = uadd(hol[u].k, c); //减少抵押物持有记录 hol[u].c = usub(hol[u].c, c); //减少相应的稳定币记录. hol[u].s = usub(hol[u].s, s); //减少该类型抵押物对应的稳定币总量. tot = usub(tot, s); //检查当前抵押物生成的稳定币总量下限. require(umul(hol[u].s, rat) >= low, "out of collateral ceiling"); //检查剩余的抵押物和稳定币之间的抵押比, 必须保持大于等于ove. uint256 cc = (umul(exr, ove) / PRE9) < pce ? umul(hol[u].c, exr) / PRE9 + 1 : umul(hol[u].c, exr) / PRE9; require(umul(hol[u].s, rat) <= cc, "bad collateral ratio"); uint256 ss = umul(s, rat); //给 @u 销毁 @s * @rat 数量的稳定币. dor.burn(u, ss); emit Payback(u, s, c); } //抵押(抵押物=>稳定币), 使用 @cnt (collateralamount) 数量的抵押物来兑换 @snt (stablecoinamount) 数量的稳定币. //给定抵押物数量 @cnt, 最大的稳定币兑换数量为 @snt = @cnt * @exr / @rat 或者 @snt = (@cnt * @price) / (@rat * @ove) //其中@cnt * @exr 或者 (@cnt * @price) / @ove 是在不考虑利息的情况下可兑换的最大数量, 但是实际上的最大可兑换数量还要考虑利息, 所以 / @rat. //例如要兑换10个稳定币, 那 @snt 不是 10, 而是 10 / rat. function borrow(address who, uint256 s, uint256 c) public { address u = who; require(hea, "system has been stopped"); require(rat != 0, "rate must not be 0"); //减少未锁定的抵押物记录. hol[u].k = usub(hol[u].k, c); //增加抵押物持有记录 hol[u].c = uadd(hol[u].c, c); //增加相应的稳定币记录 hol[u].s = uadd(hol[u].s, s); //增加该类型抵押物对应的稳定币总量 tot = uadd(tot, s); //检查当前生成的稳定币总量上限和下限 require(umul(tot, rat) <= upp && umul(hol[u].s, rat) >= low, "out of collateral ceiling"); //检查剩余的抵押物和稳定币之间的抵押比, 必须保持大于等于ove. uint256 cc = (umul(exr, ove) / PRE9) < pce ? umul(hol[u].c, exr) / PRE9 + 1 : umul(hol[u].c, exr) / PRE9; require(umul(hol[u].s, rat) <= cc, "bad collateral ratio"); uint256 ss = umul(s, rat); //给 @msg.sender 增发 @s * @rat 数量的稳定币 dor.mint(u, ss); emit Borrow(u, s, c); } /** 更新利率 */ //累加一段时间内的利率 //https://wiki.mbalib.com/wiki/%E5%90%8D%E4%B9%89%E5%88%A9%E7%8E%87 //https://wiki.mbalib.com/wiki/%E6%9C%89%E6%95%88%E5%B9%B4%E5%88%A9%E7%8E%87 //r0 = (1+(r/n))^n − 1, 有效年利率计算公式, r表示名义利率, n表示复利期数(年复利时n=1). //https://wiki.mbalib.com/wiki/%E6%9C%89%E6%95%88%E5%B9%B4%E5%88%A9%E7%8E%87 //r0 = 2.5%, 设名义年利率为2.5%, 则 r0 表示按年计息的复利率(有效年利率). //https://wiki.mbalib.com/wiki/%E8%BF%9E%E7%BB%AD%E5%A4%8D%E5%88%A9%E6%94%B6%E7%9B%8A%E7%8E%87 //r1 = ln(r0 + 1), r1 表示按年计息的连续复利收益率(对数收益率). //r2 = r1 / (60 * 60 * 24 * 365), r2 表示按秒计息的连续复利收益率 //https://wiki.mbalib.com/wiki/%E8%BF%9E%E7%BB%AD%E5%A4%8D%E5%88%A9 //F = P * e ^ (r2 * t), 连续复利计算公式, 其中: // P0 是初始值, // e 是自然对数, // r2 是按秒计息的连续复利收益率, // t 是计息周期(秒数), // F 是终值. //在计算利息时, P表示本金, F表示复利计息后的利息+本金, 但这里并不是用这个公式来直接计算利息, //而是用来算利率的增长, 所以P表示该抵押物当前的利率, F表示以r2复合增长t秒后的新利率, 而实际的利息 = 利率 * 债务. //这个公式中F和t这两个值来自于系统运行时, 但是除此之外, e, r2 都是系统外部可知的, 所以 e^r2 将被作为外部可配置的参数部分(gth); //所以 F = P * e ^ (r2 * t) // F = P * (e^r2)^t // F = P * gth ^ t //其中P表示当前利率(rat), F表示新利率(rat * gth ^ t), F - P 表示的是以r2复合增长t秒后的利率增长(可能是负值, 视配置而定), //所以最新的利率为 rat += (F - P) function rise() public { require(hea); if(now == rit) { return; } //@gth 是被表示为 @PRE(10 ** 18) 的值, 如果直接计算 @gth ** (now - rit) 结果会超级巨大, //如果先除以 @PRE(10 ** 18), 又可能会出现结果被抹成0的情况(0.XXXX...), 所以这里使用专用的 pow 算法. uint256 crat = umul(rat, pow(gth, (now - rit))); int256 b = diff(crat, rat); int256 t = int256(tot); int256 i = t * b; require(b == 0 || i / b == t); i < 0 ? dor.deci(uint256(i * -1) / PRE) : dor.inci(uint256(i) / PRE); rat = b < 0 ? usub(rat, uint256(b * -1)) : uadd(rat, uint256(b)); //处理债务的误差 uint256 dt = dor.tot(); uint256 tt = umul(tot, rat); uint256 cge = dt < tt ? tt - dt : 0; dor.inci(cge); rit = now; } /** 抵押物清算 */ //对 @who 发起清算, 减少 @who 的债务同时并拍卖相应的抵押物. function liquidate(address who) public { require(hea); hstate memory h = hol[who]; require((umul(h.c, exr) / PRE9) < umul(h.s, rat)); //计算待清算抵押物的数量, MIN(持有的抵押物数量, 单次清算数量) uint256 c = min(h.c, seg); //计算待清算的抵押物对应的稳定币数量, MIN(持有的稳定币数量, 稳定币数量 * 清算的抵押物数量 / 持有的抵押物数量) uint256 s = min(h.s, udiv(umul(h.s, c), h.c)); uint256 d = umul(s, rat); //从 @who 的持有数量中去掉待清算的抵押物记录. hol[who].c = usub(hol[who].c, c); //从 @who 的持有数量中去掉待拍卖的抵押物对应的稳定币记录. hol[who].s = usub(hol[who].s, s); //从总的稳定币数量中去掉待拍卖的抵押物对应的稳定币记录. tot = usub(tot, s); address a = IWallet(wet).get(tok); require(a != address(0), "not find asset"); IToken(tok).approve(a, c); IAsset(a).deposit(address(this), c); IAsset(a).move(address(this), lau, c); //增加系统坏账记录, 在清算回稳定币之前属于一笔无抵押物对应的坏账. //并且此时用户持有的稳定币(@debtor.hol[who])数量没有变化, //但是被清算的抵押物和对应的稳定币将以系统坏账的形式存在; dor.incb(d); ILiquidauction(lau).auction(who, address(dor), tok, c, dor.tok(), umul(d, fin), 0); } //获取用户 @who 由当前抵押物中产生的负债(稳定币总量 + 利息) function debt(address who) public view returns(uint256) { return umul(hol[who].s, rat); } //获取账户 @who 当前的抵押率 (c * rat)/(s * rat), 返回 0 表示当前用户没有抵押物记录. function cratio(address who) public view returns (uint256) { uint256 s = umul(hol[who].s, rat); uint256 c = umul(hol[who].c, pce); return s == 0 ? 0 : udiv(c, s); } function evaluateratio(uint256 c, uint256 s) public view returns(uint256) { uint256 ss = umul(s, rat); uint256 cc = umul(c, pce); return ss == 0 ? 0 : udiv(cc, ss); } function evaluateborrowc(uint256 s) public view returns(uint256) { //c = ((s * rat * ove) / pce) return udiv(umul(umul(s, rat), ove), pce); } function evaluateborrows(uint256 s) public view returns(uint256) { uint256 ss = udiv(s, rat); return umul(ss, rat) < s ? ss + 1 : ss; } function evaluatepaybacks(address who, uint256 s) public view returns(uint256) { uint256 ss = udiv(s, rat); ss = umul(ss, rat) < s ? ss + 1 : ss; return ss <= hol[who].s ? ss : hol[who].s; } function borrowable(address who) public view returns(uint256) { uint256 s = borrowedby(hol[who].c); uint256 d = debt(who); return s <= d ? 0 : usub(s, d); } //计算 @c 个抵押物最大可借的稳定币数量 ( c * pce ) / ove function borrowedby(uint256 c) public view returns(uint256) { return udiv(umul(c, pce), ove); } //@who 已借出的稳定币对应的抵押物的数量. function collateralized(address who) public view returns(uint256) { return evaluateborrowc(hol[who].s); } //@who 可取回的抵押物的数量. function uncollateralized(address who) public view returns(uint256) { uint256 c = evaluateborrowc(hol[who].s); return hol[who].c <= c ? 0 : usub(hol[who].c, c); } function move(address from, address to, uint256 amount) public auth { hol[from].k = usub(hol[from].k, amount); hol[to].k = uadd(hol[to].k, amount); } function deposit(address who, uint256 amount) public payable { hol[who].k = uadd(hol[who].k, amount); if(tok == address(0)) { require(amount == msg.value, "amount mismatch with msg.value"); return; } require(IToken(tok).transferFrom(who, address(this), amount)); IJoined(jin).join(who); emit Deposit(msg.sender, who, amount); } function withdraw(address payable who, uint256 amount) public { hol[who].k = usub(hol[who].k, amount); if(tok == address(0)) { who.transfer(amount); return; } require(IToken(tok).transfer(who, amount)); emit Withdraw(msg.sender, who, amount); } function holc(address who) public view returns(uint256) { return hol[who].c; } function hols(address who) public view returns(uint256) { return hol[who].s; } function holk(address who) public view returns(uint256) { return hol[who].k; } function pow(uint256 x, uint256 n, uint256 base) internal pure returns (uint256 z) { //TODO; } function pow(uint256 x, uint256 n) internal pure returns (uint256 z) { return pow(x, n, PRE); } function min(uint256 x, uint256 y) internal pure returns(uint256 z) { z = (x <= y ? x : y); } function umul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y; require(y == 0 || z / y == x); z = z / PRE; } function udiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * PRE; require(x == 0 || z / x == PRE); z = z / y; } function usub(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x >= y); z = x - y; } function uadd(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; require (z >= x); } function diff(uint256 x, uint256 y) internal pure returns (int z) { z = int(x) - int(y); require(int(x) >= 0 && int(y) >= 0); } /** 系统内部精度 */ uint256 constant public PRE9 = 10 ** 9; uint256 constant public PRE = 10 ** 18; }
获取账户 @who 当前的抵押率 (c rat)/(s rat), 返回 0 表示当前用户没有抵押物记录.
function cratio(address who) public view returns (uint256) { uint256 s = umul(hol[who].s, rat); uint256 c = umul(hol[who].c, pce); return s == 0 ? 0 : udiv(c, s); }
7,280,044
./full_match/4/0xdACEFC3449dE5cB7f29921DA711Ffa3f37BBE4B8/sources/browser/hook.sol
use level 1 to 6 not 0 to 5booster for level 0
function withdrawTeamActivationGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<8;i++) { totalAmount += teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]; paidTeamActivationGain[_userId][i] = teamActivationGain[_userId][i]; } } if(totalAmount>0 ) withdrawToken(totalAmount, _userId); return true; }
12,476,597
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_198(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,453,911
/** *Submitted for verification at Etherscan.io on 2021-07-19 */ /// // GasBack Technology // https://gasback.tech/ // // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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}. */ 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; } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity >=0.6.4; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract BEP20 is Context, IBEP20, Ownable { 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 bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the name of the token. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom (address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance') ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer (address sender, address recipient, uint256 amount) internal { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve (address owner, address spender, uint256 amount) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance')); } } // GasFuel contract GasBackFuel is BEP20('GasFuel', 'GASF') { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } 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, 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; } } 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); } 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); } } } } /** * @title SafeBEP20 * @dev Wrappers around BEP20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer(IBEP20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IBEP20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IBEP20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeBEP20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IBEP20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IBEP20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeBEP20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IBEP20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeBEP20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeBEP20: BEP20 operation did not succeed"); } } } // MasterChef is the Owner of GasBackFuel and has super powers. // He keeps track of rewards and the most recent TX Gas Price. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once governance is sufficiently // distributed and the community can be shown to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Most recent GasPrice, used for tracking on Web dApp uint256 public latestGasPrice = 0; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of Gas // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accGasPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accGasPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Gas to distribute per block. uint256 lastRewardBlock; // Last block number that Gas distribution occurs. uint256 accGasPerShare; // Accumulated Gas per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points } // The GasBackFuel Token GasBackFuel public gasback; // Dev address. address public devaddr; // Gas tokens created per block. uint256 public gasbackPerBlock; // Bonus muliplier for early gasback makers. uint256 public constant BONUS_MULTIPLIER = 1; // Treasury address address public treasuryAddress; // Ensure we can't add same pool twice mapping (address => bool) private poolIsAdded; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( GasBackFuel _gasback, address _devaddr, address _treasuryAddress, uint256 _gasbackPerBlock, uint256 _startBlock ) public { gasback = _gasback; devaddr = _devaddr; treasuryAddress = _treasuryAddress; gasbackPerBlock = _gasbackPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } // EDIT: Don't add same pool twice, fixed in code with check require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGasPerShare: 0, depositFeeBP: _depositFeeBP })); } // Update the given pool's Gas allocation point and deposit fee. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending Gass on frontend. function pendingGas(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGasPerShare = pool.accGasPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gasbackReward = multiplier.mul(gasbackPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accGasPerShare = accGasPerShare.add(gasbackReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accGasPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { // Added to set recent latestGasPrice latestGasPrice = tx.gasprice; 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 gasbackReward = multiplier.mul(gasbackPerBlock).mul(pool.allocPoint).div(totalAllocPoint); gasback.mint(devaddr, gasbackReward.div(10)); gasback.mint(address(this), gasbackReward); pool.accGasPerShare = pool.accGasPerShare.add(gasbackReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Gas allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accGasPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeGasTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(treasuryAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); }else{ user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accGasPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGasPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeGasTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accGasPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe gasback transfer function, just in case if rounding error causes pool to not have enough Gas. function safeGasTransfer(address _to, uint256 _amount) internal { uint256 gasbackBal = gasback.balanceOf(address(this)); if (_amount > gasbackBal) { gasback.transfer(_to, gasbackBal); } else { gasback.transfer(_to, _amount); } } function dev(address _devaddr) public onlyOwner { devaddr = _devaddr; } function setTreasuryAddress(address _treasuryAddress) public onlyOwner { treasuryAddress = _treasuryAddress; } function updateEmissionRate(uint256 _gasbackPerBlock) public onlyOwner { massUpdatePools(); gasbackPerBlock = _gasbackPerBlock; } }
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGasPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeGasTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accGasPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
2,179,030
// 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); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.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); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.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 Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } // File contracts/erc721a.sol error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; //Token Base URI string private _baseURI; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(_baseURI).length != 0 ? string(abi.encodePacked(_baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function baseURI() internal view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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 Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract MeanBabies is ERC721A, Ownable { string public MEANBABIES_PROVENANCE = ""; uint256 public MEANBABY_PRICE = 0.0678 ether; uint256 public WHITELIST_PRICE = 0.05 ether; bool private IS_BABIES_MINT_ACTIVE; bool private IS_WHITELIST_MINT_ACTIVE; bool private DEV_RESERVED; bool private RESERVED; mapping(address => uint256) private IS_WHITELISTED; mapping(address => uint256) private FREE_WHITELIST; mapping(address => uint256) private WHITELISTED_MINTED; address payable private dev = payable(0xE49d854e9b1502aAF4f75390B356b47f38328745); address payable private project = payable(0xABd8aD295AC2339a5Cd0e578417da50f2A69e917); constructor()ERC721A("Mean Babies", "MB") { } /** * Withdraw and distribute eths collected from mint */ function withdraw() external { uint balance = address(this).balance; dev.transfer((balance*15)/100); project.transfer((balance*85)/100); } /** * Only Owner: Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) external onlyOwner { MEANBABIES_PROVENANCE = provenanceHash; } /** * Only Owner: Set Base URI for NFTs Metadata */ function setBaseURI(string memory baseURI) external onlyOwner { _setBaseURI(baseURI); } /** * Only Owner: Enable/Disable public minting */ function flipPublicMintState() external onlyOwner { IS_BABIES_MINT_ACTIVE = !IS_BABIES_MINT_ACTIVE; } /** * Only Owner: Enable/Disable whitelist minting */ function flipWhitelistMintState() external onlyOwner { IS_WHITELIST_MINT_ACTIVE = !IS_WHITELIST_MINT_ACTIVE; } /** * Only Owner: Whitelist an address for free presale minting only one per address */ function freeWhitelist(address[] calldata wallets) external onlyOwner { for(uint i=0; i<wallets.length; i++) { FREE_WHITELIST[wallets[i]] = 1; } } /** * Only Owner: Whitelist an address for presale minting */ function whitelist(address[] calldata wallets) external onlyOwner { for(uint i=0; i<wallets.length; i++) { IS_WHITELISTED[wallets[i]] = 1; } } /** * Only Owner: Reserve Mean babies for dev */ function reserveDev() external onlyOwner { require(!DEV_RESERVED, "Can only reserve once"); _safeMint(dev, 2); DEV_RESERVED = true; } /** * Only Owner: Reserve Mean babies for team and marketing wallets */ function reserveBabies(address team, address marketing) external onlyOwner { require(!RESERVED, "Can only reserve once"); _safeMint(team, 6); _safeMint(marketing, 45); RESERVED = true; } /** * Mints Mean baby for free whitelisted addresses only one per account */ function MintFree() external { require(IS_WHITELIST_MINT_ACTIVE, "Mean Babies Whitelist Mint is Not Active"); require(FREE_WHITELIST[msg.sender] == 1, "Your are not Whitelisted For Free mint OR have minted before"); require((totalSupply()+1) <= 3333, "Mean Babies Mint Finished"); FREE_WHITELIST[msg.sender] = 2; _safeMint(msg.sender, 1); } /** * Mints Mean babies for whitelisted addresses only */ function MintWhitelist(uint256 numberOfTokens) external payable { require(IS_WHITELIST_MINT_ACTIVE, "Mean Babies Whitelist Mint is Not Active"); require(IS_WHITELISTED[msg.sender] == 1 || FREE_WHITELIST[msg.sender] == 2, "Your are not Whitelisted For presale"); require(WHITELISTED_MINTED[msg.sender]+numberOfTokens <= 2, "Max 2 nfts per whitelisted address are allowed in presale"); require((totalSupply()+numberOfTokens) <= 3333, "Mean Babies Mint Finished"); require(msg.value == (numberOfTokens * WHITELIST_PRICE), "Wrong Eth value sent"); WHITELISTED_MINTED[msg.sender] += numberOfTokens; _safeMint(msg.sender, numberOfTokens); } /** * Mints Remaining Mean Babies after reserve and whitelist mint */ function mintBabies(uint256 numberOfTokens) external payable { require(IS_BABIES_MINT_ACTIVE, "Mean Babies Mint is Not Active"); require(numberOfTokens <= 20, "Max 20 Mean Babies Per Transaction are allowed"); require((totalSupply()+numberOfTokens) <= 3333, "Mean Babies Mint Finished"); require(msg.value == (numberOfTokens * MEANBABY_PRICE), "Wrong Eth value sent"); _safeMint(msg.sender, numberOfTokens); } }
Only Owner: Enable/Disable public minting/
function flipPublicMintState() external onlyOwner { IS_BABIES_MINT_ACTIVE = !IS_BABIES_MINT_ACTIVE; }
14,578,249
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; /// @dev Governance Gearbox token /// based on https://github.com/Uniswap/governance/blob/master/contracts/Uni.sol contract GearToken { /// @notice EIP-20 token name for this token string public constant name = "Gearbox"; /// @notice EIP-20 token symbol for this token string public constant symbol = "GEAR"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 10_000_000_000e18; // 10 billion Gear // Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; // Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 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 The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Flag which allows token transfers bool public transfersAllowed; /// @notice Contract owner which can allow token transfers address public manager; /// @notice Miner address which can send tokens during account mining address public miner; /// @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, uint256 previousBalance, uint256 newBalance ); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval( address indexed owner, address indexed spender, uint256 amount ); event OwnershipTransferred(address indexed owner, address indexed newOwner); event MinerSet(address indexed miner); event TransferAllowed(); modifier managerOnly() { require(msg.sender == manager, "Gear::caller is not the manager"); _; } /** * @notice Construct a new Gear token * @param account The initial account to grant all the tokens */ constructor(address account) { require(account != address(0), "Zero address is not allowed"); balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); manager = msg.sender; transfersAllowed = false; } function transferOwnership(address newManager) external managerOnly // T:[GT-3] { require(newManager != address(0), "Zero address is not allowed"); // T:[GT-5] emit OwnershipTransferred(manager, newManager); // T:[GT-6] manager = newManager; // T:[GT-6] } function setMiner(address _miner) external managerOnly // T:[GT-3] { require(_miner != address(0), "Zero address is not allowed"); miner = _miner; // T:[GT-4] emit MinerSet(miner); // T:[GT-4] } function allowTransfers() external managerOnly // T:[GT-3] { transfersAllowed = true; // T:[GT-1] emit TransferAllowed(); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Gear::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline 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 permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Gear::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline ) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Gear::permit: invalid signature"); require(signatory == owner, "Gear::permit: unauthorized"); require(block.timestamp <= deadline, "Gear::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96( rawAmount, "Gear::transfer: amount exceeds 96 bits" ); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96( rawAmount, "Gear::approve: amount exceeds 96 bits" ); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Gear::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @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, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "Gear::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "Gear::delegateBySig: invalid nonce" ); require( block.timestamp <= expiry, "Gear::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 (uint96) { 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, uint256 blockNumber) external view returns (uint96) { require( blockNumber < block.number, "Gear::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; 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]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require( transfersAllowed || msg.sender == manager || msg.sender == miner, "Gear::transfers are forbidden" ); require( src != address(0), "Gear::_transferTokens: cannot transfer from the zero address" ); require( dst != address(0), "Gear::_transferTokens: cannot transfer to the zero address" ); balances[src] = sub96( balances[src], amount, "Gear::_transferTokens: transfer amount exceeds balance" ); balances[dst] = add96( balances[dst], amount, "Gear::_transferTokens: transfer amount overflows" ); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96( srcRepOld, amount, "Gear::_moveVotes: vote amount underflows" ); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96( dstRepOld, amount, "Gear::_moveVotes: vote amount overflows" ); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32( block.number, "Gear::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // 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; } }
Approve `spender` to transfer up to `amount` from `src` This will overwrite the approval amount for `spender` spender The address of the account which may transfer tokens rawAmount The number of tokens that are approved (2^256-1 means infinite) return Whether or not the approval succeeded/
function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); amount = safe96(rawAmount, "Gear::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
5,708,668
pragma solidity >=0.0.0; //eventTest is used to test various types of solidity events contract eventTest { address owner; constructor() public{ owner = msg.sender; } event multiArgsEvent(address addr,bytes32 name, bool boolValue, int number, string methondName); event Uint256OneEvent(uint256); event Uint256OneIndexEvent(uint256 indexed); event Uint256TwoIndexEvent(uint256 indexed,uint256 index); event Uint256TwoIndexFirstEvent(uint256 indexed,uint256); event Uint256TwoIndexSecEvent(uint256,uint256 index); event Int256OneEvent(int256); event Int256OneIndexEvent(int256 indexed); event Int256TwoIndexEvent(int256 indexed,int256 index); event Int256TwoIndexFirstEvent(int256 indexed,int256); event Int256TwoIndexSecEvent(int256,int256 index); event AddressOneIndexEvent(address indexed); event AddressTwoIndexEvent(address indexed,address indexed); event AddressTwoIndexFirstEvent(address indexed,address); event AddressTwoIndexSecEvent(address,address indexed); event BoolOneIndexEvent(bool indexed); event BoolTwoIndexEvent(bool indexed,bool indexed); event BoolTwoIndexFirstEvent(bool indexed,bool); event BoolTwoIndexSecEvent(bool,bool indexed); event StringOneIndexEvent(string indexed); event StringTwoIndexEvent(string indexed,string indexed); event StringTwoIndexFirstEvent(string indexed,string); event StringTwoIndexSecEvent(string,string indexed); event Byte32OneIndexEvent(bytes32 indexed); event Byte32TwoIndexEvent(bytes32 indexed,bytes32 indexed); event Byte32TwoIndexFirstEvent(bytes32 indexed,bytes32); event Byte32TwoIndexSecEvent(bytes32,bytes32 indexed); event BytesOtherTypeEvent(bytes2,bytes5,bytes20); event BytesOtherTypeEventIndexed(bytes2 indexed,bytes5 indexed,bytes20 indexed); event SameNameEvent(string,int); event SameNameEvent(int,string ); // 测试byte相关事件,此例子中测试了byte2,byte23,byte20,可自定义修改byte长度,最大长度为byte32 function testBytes() public payable { bytes2 b2 = 0xabcd; bytes5 b5 = "hello"; bytes20 b20 = hex"1234"; emit BytesOtherTypeEvent(b2,b5,b20); emit BytesOtherTypeEventIndexed(b2,b5,b20); } // 测试Uint相关事件,此例子中仅测试了uint256,可自定义修改uint长度,最大长度为uint256 function testUint256Event(uint256 a,uint256 b)public payable{ emit Uint256OneEvent(a); emit Uint256OneIndexEvent(a); emit Uint256TwoIndexEvent(a,b); emit Uint256TwoIndexFirstEvent(a,b); emit Uint256TwoIndexSecEvent(a,b); } // 测试int相关事件,此例子中仅测试了int256,可自定义修改int长度,最大长度为int256 function testint256Event(int256 a,int256 b)public payable{ emit Int256OneEvent(a); emit Int256OneIndexEvent(a); emit Int256TwoIndexEvent(a,b); emit Int256TwoIndexFirstEvent(a,b); emit Int256TwoIndexSecEvent(a,b); } // 测试Address相关事件,Address为一个长度为40的16进制数字 function testAddresxsEvent(address a,address b) public payable{ emit AddressOneIndexEvent(a); emit AddressTwoIndexEvent(a,b); emit AddressTwoIndexFirstEvent(a,b); emit AddressTwoIndexSecEvent(a,b); } // 测试Bool相关事件 function testBoolEvent(bool a,bool b) public payable{ emit BoolOneIndexEvent(a); emit BoolTwoIndexEvent(a,b); emit BoolTwoIndexFirstEvent(a,b); emit BoolTwoIndexSecEvent(a,b); } //测试String相关事件,带有indexed的参数在事件订阅中返回为该字符串的 Keccak256Hash 哈希值 function testStringEvent(string memory a, string memory b) public payable{ emit StringOneIndexEvent(a); emit StringTwoIndexEvent(a,b); emit StringTwoIndexFirstEvent(a,b); emit StringTwoIndexSecEvent(a,b); } //测试bytes32相关事件,测试是否带有indexed以及indexed的顺序对事件的影响 function testBytes32Event(bytes32 a, bytes32 b) public payable{ emit Byte32OneIndexEvent(a); emit Byte32TwoIndexEvent(a,b); emit Byte32TwoIndexFirstEvent(a,b); emit Byte32TwoIndexSecEvent(a,b); } // 测试所有类型参数的事件。该事件参数包好了以上各个类型 function MultiArgs() public payable{ bytes32 name = "bytes32"; int number = 25; emit multiArgsEvent(owner,name,true,number,"multiArgsEvent is tested for solidity type"); } //单独测试不带Indexed的 Uint256 function TestUint256WithoutIndexed(uint256 a) public payable{ emit Uint256OneEvent(a); } // 单独测试带有Indexed的Uint256 function TestUint256Indexed(uint256 a) public payable{ emit Uint256OneIndexEvent(a); } // 测试相同名字,参数不同的事件 function TestSameNameEvent(int n,string memory s) public payable{ emit SameNameEvent(n,s); emit SameNameEvent(s,n); } }
测试String相关事件,带有indexed的参数在事件订阅中返回为该字符串的 Keccak256Hash 哈希值
function testStringEvent(string memory a, string memory b) public payable{ emit StringOneIndexEvent(a); emit StringTwoIndexEvent(a,b); emit StringTwoIndexFirstEvent(a,b); emit StringTwoIndexSecEvent(a,b); }
12,663,610
/** *Submitted for verification at Etherscan.io on 2021-07-12 */ // Verified using https://dapp.tools // hevm: flattened sources of src/lender/adapters/deployer.sol // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.6.12; ////// src/lender/fabs/interfaces.sol /* pragma solidity >=0.6.12; */ interface ReserveFabLike_1 { function newReserve(address) external returns (address); } interface AssessorFabLike_2 { function newAssessor() external returns (address); } interface TrancheFabLike_1 { function newTranche(address, address) external returns (address); } interface CoordinatorFabLike_2 { function newCoordinator(uint) external returns (address); } interface OperatorFabLike_1 { function newOperator(address) external returns (address); } interface MemberlistFabLike_1 { function newMemberlist() external returns (address); } interface RestrictedTokenFabLike_1 { function newRestrictedToken(string calldata, string calldata) external returns (address); } interface PoolAdminFabLike { function newPoolAdmin() external returns (address); } interface ClerkFabLike { function newClerk(address, address) external returns (address); } interface TinlakeManagerFabLike { function newTinlakeManager(address, address, address, address, address, address, address, address) external returns (address); } ////// src/lender/adapters/deployer.sol /* pragma solidity >=0.6.12; */ /* import { ClerkFabLike, TinlakeManagerFabLike } from "../fabs/interfaces.sol"; */ interface LenderDeployerLike_1 { function coordinator() external returns (address); function assessor() external returns (address); function reserve() external returns (address); function seniorOperator() external returns (address); function seniorTranche() external returns (address); function seniorToken() external returns (address); function currency() external returns (address); function poolAdmin() external returns (address); function seniorMemberlist() external returns (address); } interface PoolAdminLike_1 { function rely(address) external; function relyAdmin(address) external; } interface FileLike_2 { function file(bytes32 name, uint value) external; } interface MemberlistLike_1 { function updateMember(address, uint) external; } interface MgrLike { function rely(address) external; function file(bytes32 name, address value) external; function lock(uint) external; } interface AuthLike_2 { function rely(address) external; function deny(address) external; } interface DependLike_2 { function depend(bytes32, address) external; } contract AdapterDeployer { ClerkFabLike public clerkFab; TinlakeManagerFabLike public mgrFab; address public clerk; address public mgr; address public root; LenderDeployerLike_1 public lenderDeployer; address deployUsr; constructor(address root_, address clerkFabLike_, address mgrFabLike_) { root = root_; clerkFab = ClerkFabLike(clerkFabLike_); mgrFab = TinlakeManagerFabLike(mgrFabLike_); deployUsr = msg.sender; } function deployClerk(address lenderDeployer_) public { require(deployUsr == msg.sender && address(clerk) == address(0) && LenderDeployerLike_1(lenderDeployer_).seniorToken() != address(0)); lenderDeployer = LenderDeployerLike_1(lenderDeployer_); clerk = clerkFab.newClerk(lenderDeployer.currency(), lenderDeployer.seniorToken()); address assessor = lenderDeployer.assessor(); address reserve = lenderDeployer.reserve(); address seniorTranche = lenderDeployer.seniorTranche(); address seniorMemberlist = lenderDeployer.seniorMemberlist(); address poolAdmin = lenderDeployer.poolAdmin(); // clerk dependencies DependLike_2(clerk).depend("coordinator", lenderDeployer.coordinator()); DependLike_2(clerk).depend("assessor", assessor); DependLike_2(clerk).depend("reserve", reserve); DependLike_2(clerk).depend("tranche", seniorTranche); DependLike_2(clerk).depend("collateral", lenderDeployer.seniorToken()); // clerk as ward AuthLike_2(seniorTranche).rely(clerk); AuthLike_2(reserve).rely(clerk); AuthLike_2(assessor).rely(clerk); // reserve can draw and wipe on clerk DependLike_2(reserve).depend("lending", clerk); AuthLike_2(clerk).rely(reserve); // allow clerk to hold seniorToken MemberlistLike_1(seniorMemberlist).updateMember(clerk, type(uint256).max); DependLike_2(assessor).depend("lending", clerk); AuthLike_2(clerk).rely(poolAdmin); AuthLike_2(clerk).rely(root); } function deployMgr(address dai, address daiJoin, address end, address vat, address vow, address liq, address spotter, address jug, uint matBuffer) public { require(deployUsr == msg.sender && address(clerk) != address(0) && address(mgr) == address(0) && lenderDeployer.seniorToken() != address(0)); // deploy mgr mgr = mgrFab.newTinlakeManager(dai, daiJoin, lenderDeployer.seniorToken(), lenderDeployer.seniorOperator(), lenderDeployer.seniorTranche(), end, vat, vow); wireClerk(mgr, vat, spotter, jug, matBuffer); // setup mgr MgrLike mkrMgr = MgrLike(mgr); mkrMgr.rely(clerk); mkrMgr.file("liq", liq); mkrMgr.file("end", end); mkrMgr.file("owner", clerk); // rely root, deny adapter deployer AuthLike_2(mgr).rely(root); AuthLike_2(mgr).deny(address(this)); } // This is separated as the system tests don't use deployMgr, but do need the clerk wiring function wireClerk(address mgr_, address vat, address spotter, address jug, uint matBuffer) public { require(deployUsr == msg.sender && address(clerk) != address(0)); // wire clerk DependLike_2(clerk).depend("mgr", mgr_); DependLike_2(clerk).depend("spotter", spotter); DependLike_2(clerk).depend("vat", vat); DependLike_2(clerk).depend("jug", jug); // set the mat buffer FileLike_2(clerk).file("buffer", matBuffer); // rely root, deny adapter deployer AuthLike_2(clerk).deny(address(this)); MemberlistLike_1(lenderDeployer.seniorMemberlist()).updateMember(mgr_, type(uint256).max); } }
clerk dependencies clerk as ward reserve can draw and wipe on clerk allow clerk to hold seniorToken
function deployClerk(address lenderDeployer_) public { require(deployUsr == msg.sender && address(clerk) == address(0) && LenderDeployerLike_1(lenderDeployer_).seniorToken() != address(0)); lenderDeployer = LenderDeployerLike_1(lenderDeployer_); clerk = clerkFab.newClerk(lenderDeployer.currency(), lenderDeployer.seniorToken()); address assessor = lenderDeployer.assessor(); address reserve = lenderDeployer.reserve(); address seniorTranche = lenderDeployer.seniorTranche(); address seniorMemberlist = lenderDeployer.seniorMemberlist(); address poolAdmin = lenderDeployer.poolAdmin(); DependLike_2(clerk).depend("coordinator", lenderDeployer.coordinator()); DependLike_2(clerk).depend("assessor", assessor); DependLike_2(clerk).depend("reserve", reserve); DependLike_2(clerk).depend("tranche", seniorTranche); DependLike_2(clerk).depend("collateral", lenderDeployer.seniorToken()); AuthLike_2(seniorTranche).rely(clerk); AuthLike_2(reserve).rely(clerk); AuthLike_2(assessor).rely(clerk); DependLike_2(reserve).depend("lending", clerk); AuthLike_2(clerk).rely(reserve); MemberlistLike_1(seniorMemberlist).updateMember(clerk, type(uint256).max); DependLike_2(assessor).depend("lending", clerk); AuthLike_2(clerk).rely(poolAdmin); AuthLike_2(clerk).rely(root); }
12,867,777
pragma solidity ^0.5.0; import "../interfaces/IACATRStorage.sol"; import "./BaseARStorage.sol"; /** * @title Application CAT registry storage */ contract ACATRStorage is BaseARStorage, IACATRStorage { // Declare storage for the "CAT registry" application indexes // application address => index mapping(address => uint) CATAppsIndexes; // Declare storage for the registred applications // application address => status (true - registred) mapping(address => bool) registredCATApps; // Declare storage for the list of the all applications in the "CAT registry" address[] CATApps; // Writes info in the log when an added application in the "CAT registry" event CATAppCreated(address indexed app); // Writes info in the log when application was removed from the "CAT registry" event CATAppRemoved(address indexed app); // Writes info to the log when application in the "CAT registry" was updated event CATAppStatusUpdated(address indexed app, bool status); /// Events emmiters. Write info about any state changes to the log. /// Allowed only for the Application Registry. /** * @notice Write info to the log when added new application * @param app Application address */ function emitCATAppCreated(address app) public onlyApplicationRegistry(msg.sender) { emit CATAppCreated(app); } /** * @notice Write info to the log when application was removed * @param app Application to be removed */ function emitCATAppRemoved(address app) public onlyApplicationRegistry(msg.sender) { emit CATAppRemoved(app); } /** * @notice Write info to the log when application was updated * @param app Application to be updated * @param status New application status */ function emitCATAppStatusUpdated(address app, bool status) public onlyApplicationRegistry(msg.sender) { emit CATAppStatusUpdated(app, status); } /// Methods which updates the storage. Allowed only for the Application Registry. /** * @notice Set application index in the "CAT registry" * @param app Application address * @param index Application index */ function setCATAppIndex(address app, uint index) public onlyApplicationRegistry(msg.sender) { CATAppsIndexes[app] = index; } /** * @notice Add application to the index in the registry * @param app Application address * @param index Application index */ function addCATAppToIndex(address app, uint index) public onlyApplicationRegistry(msg.sender) { CATApps[index] = app; } /** * @notice Push new application * @param app Application address */ function pushNewCATApp(address app) public onlyApplicationRegistry(msg.sender) { CATApps.push(app); } /** * @notice Remove CAT application from the list * @param index Index of the application that will be removed */ function deleteCATAppFromTheList(uint index) public onlyApplicationRegistry(msg.sender) { delete CATApps[index]; } /** * @notice Remove CAT application index * @param app Application address */ function deleteCATAppIndex(address app) public onlyApplicationRegistry(msg.sender) { delete CATAppsIndexes[app]; } /** * @notice Update length of the CAT applications list * @param length New length */ function setCATAppsLength(uint length) public onlyApplicationRegistry(msg.sender) { CATApps.length = length; } /** * @notice Set CAT application status * @param index Application index * @param status Application statu */ function setCATAppStatus(uint index, bool status) public onlyApplicationRegistry(msg.sender) { registredCATApps[CATApps[index]] = status; } /** * @notice Update application registration status * @param app Application address * @param status Status to be set */ function setCATAppRegistrationStatus(address app, bool status) public onlyApplicationRegistry(msg.sender) { registredCATApps[app] = status; } /// Getters. Public methods which are allowed for anyone. /** * @notice Returns application status from the CAT registry * @param index Application index */ function getCATAppStatus(uint index) public view returns (bool) { return registredCATApps[CATApps[index]]; } /** * @notice Returns application status from the CAT registry. * @notice Shows whether an application is registered or not. * @param app Application address */ function getCATAppStatusByAddress(address app) public view returns (bool) { return registredCATApps[app]; } /** * @notice Returns all applications in the "CAT registry" */ function getCATApplications() public view returns (address[] memory) { return CATApps; } /** * @notice Returns application index from the "CAT registry" * @param app Application address */ function getCATAppIndex(address app) public view returns (uint) { return CATAppsIndexes[app]; } /** * @notice Returns applications length */ function getCATAppsLength() public view returns (uint) { return CATApps.length; } /** * @notice Returns application by index * @param index Application index */ function getCATAppByIndex(uint index) public view returns (address) { return CATApps[index]; } }
Set CAT application status index Application index status Application statu/
function setCATAppStatus(uint index, bool status) public onlyApplicationRegistry(msg.sender) { registredCATApps[CATApps[index]] = status; }
14,035,016
./partial_match/1/0x36afc7E590Bf5cBe512d2B3BFEe03B2E96bD4Abc/sources/X2Token.sol
Sets `amsousnt` as the allowanceacbaoubnt of `spender` amsousntover the caller's acbaoubnttokens./
function _approve( address owner, address spender, uint256 amsousnt ) 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] = amsousnt; emit Approval(owner, spender, amsousnt);
2,844,697
./partial_match/1/0x451D644268365D8062F02141aCaEc0F8f138FC97/sources/contracts/interfaces/IBestDexV3PoolDeployer.sol
An interface for a contract that is capable of deploying BestDexV3 V3 Pools A contract that constructs a pool must implement this to pass arguments to the pool This is used to avoid having constructor arguments in the pool contract, which results in the init code hash of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain
interface IBestDexV3PoolDeployer { function parameters() external view returns ( address factory, address token0, address token1, uint24 fee, int24 tickSpacing ); pragma solidity >=0.5.0; }
4,150,252
./full_match/71401/0x1281b4CD5d8C0Ec5Ce282E28b00F668D8AC13b2B/sources/contracts/configuration/ParametersProvider.sol
Calculates protocol fee. Calculates protocol fee from the premium returned by premium engine premium The premium amount return The calculated protocol fee
function calculateProtocolFee(uint256 premium) external pure returns (uint256) { return (premium * PROTOCOL_FEE) / 100; }
7,100,204
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract DevTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @dev Developer wallet address payable public devWallet; /// @dev SDVD contract address address public sdvd; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @dev Uniswap LP address address public pairAddress; /// @notice Release balance every 1 hour to dev wallet uint256 public releaseThreshold = 1 hours; /// @dev Last release timestamp uint256 public releaseTime; constructor (address _uniswapRouter, address _sdvd) public { // Set dev wallet devWallet = msg.sender; // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set uniswap factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); // Get weth address weth = uniswapRouter.WETH(); // Set SDVD address sdvd = _sdvd; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(_uniswapRouter, uint256(- 1)); // Set initial release time releaseTime = block.timestamp; } /* ========== Owner Only ========== */ function init() external onlyOwner { // Get pair address after init because we wait until pair created in lord of coin pairAddress = uniswapFactory.getPair(sdvd, weth); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release SDVD to market regardless the price so dev doesn't own any SDVD from 0.5% fee. /// This is to protect SDVD holders. function release() external { _release(); } /* ========== Internal ========== */ function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Get SDVD balance uint256 sdvdBalance = IERC20(sdvd).balanceOf(address(this)); // If there is SDVD in this contract // and there is enough liquidity to swap if (sdvdBalance > 0 && IERC20(sdvd).balanceOf(pairAddress) >= sdvdBalance) { address[] memory path = new address[](2); path[0] = sdvd; path[1] = weth; // Swap SDVD to ETH on uniswap // uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( sdvdBalance, 0, path, devWallet, block.timestamp.add(30 minutes) ); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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: Unlicensed 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 migrator() 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 setMigrator(address) external; } // SPDX-License-Identifier: Unlicensed 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.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: Unlicensed 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: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IWETH.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/IBPool.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract TradingTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Received(address indexed from, uint256 amount); /// @dev Lord of coin address address public controller; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev Balancer pool WETH-MUSD address balancerPool; /// @dev WETH address address weth; /// @dev mUSD contract address address musd; /// @dev SDVD contract address address public sdvd; /// @dev Uniswap LP address address public pairAddress; /// @notice Release balance as sharing pool profit every 1 hour uint256 public releaseThreshold = 1 hours; /// @dev Last release timestamp uint256 public releaseTime; constructor (address _uniswapRouter, address _balancerPool, address _sdvd, address _musd) public { // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set uniswap factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); // Get weth address weth = uniswapRouter.WETH(); // Set balancer pool balancerPool = _balancerPool; // Set SDVD address sdvd = _sdvd; // Set mUSD address musd = _musd; // Approve uniswap to spend SDVD IERC20(sdvd).approve(_uniswapRouter, uint256(- 1)); // Approve balancer to spend WETH IERC20(weth).approve(balancerPool, uint256(- 1)); // Set initial release time releaseTime = block.timestamp; } receive() external payable { emit Received(msg.sender, msg.value); } /* ========== Owner Only ========== */ function init(address _controller) external onlyOwner { // Set Lord of coin address controller = _controller; // Get pair address pairAddress = ILordOfCoin(controller).sdvdEthPairAddress(); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release SDVD to be added as profit function release() external { _release(); } /* ========== Internal ========== */ function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Get SDVD balance uint256 sdvdBalance = IERC20(sdvd).balanceOf(address(this)); // If there is SDVD in this contract // and there is enough liquidity to swap if (sdvdBalance > 0 && IERC20(sdvd).balanceOf(pairAddress) >= sdvdBalance) { // Use uniswap since this contract is registered as no fee address for swapping SDVD to ETH // Swap path address[] memory path = new address[](2); path[0] = sdvd; path[1] = weth; // Swap SDVD to ETH on uniswap // uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( sdvdBalance, 0, path, address(this), block.timestamp.add(30 minutes) ); // Get all ETH in this contract uint256 ethAmount = address(this).balance; // Convert ETH to WETH IWETH(weth).deposit{ value: ethAmount }(); // Swap WETH to mUSD (uint256 musdAmount,) = IBPool(balancerPool).swapExactAmountIn(weth, ethAmount, musd, 0, uint256(-1)); // Send it to Lord of Coin IERC20(musd).safeTransfer(controller, musdAmount); // Deposit profit ILordOfCoin(controller).depositTradingProfit(musdAmount); } } } } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface ILordOfCoin { function marketOpenTime() external view returns (uint256); function dvd() external view returns (address); function sdvd() external view returns (address); function sdvdEthPairAddress() external view returns (address); function buy(uint256 musdAmount) external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function buyTo(address recipient, uint256 musdAmount) external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function buyFromETH() payable external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sell(uint256 dvdAmount) external returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sellTo(address recipient, uint256 dvdAmount) external returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sellToETH(uint256 dvdAmount) external returns (uint256 returnedETH, uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function claimDividend() external returns (uint256 net, uint256 fee); function claimDividendTo(address recipient) external returns (uint256 net, uint256 fee); function claimDividendETH() external returns (uint256 net, uint256 fee, uint256 receivedETH); function checkSnapshot() external; function releaseTreasury() external; function depositTradingProfit(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IBPool { function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); function isBound(address t) external view returns (bool); function getNumTokens() external view returns (uint); function getCurrentTokens() external view returns (address[] memory tokens); function getFinalTokens() external view returns (address[] memory tokens); function getDenormalizedWeight(address token) external view returns (uint); function getTotalDenormalizedWeight() external view returns (uint); function getNormalizedWeight(address token) external view returns (uint); function getBalance(address token) external view returns (uint); function getSwapFee() external view returns (uint); function getController() external view returns (address); function setSwapFee(uint swapFee) external; function setController(address manager) external; function setPublicSwap(bool public_) external; function finalize() external; function bind(address token, uint balance, uint denorm) external; function rebind(address token, uint balance, uint denorm) external; function unbind(address token) external; function gulp(address token) external; function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint spotPrice); function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint spotPrice); function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external; function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external returns (uint tokenAmountOut, uint spotPriceAfter); function swapExactAmountOut( address tokenIn, uint maxAmountIn, address tokenOut, uint tokenAmountOut, uint maxPrice ) external returns (uint tokenAmountIn, uint spotPriceAfter); function joinswapExternAmountIn( address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function joinswapPoolAmountOut( address tokenIn, uint poolAmountOut, uint maxAmountIn ) external returns (uint tokenAmountIn); function exitswapPoolAmountIn( address tokenOut, uint poolAmountIn, uint minAmountOut ) external returns (uint tokenAmountOut); function exitswapExternAmountOut( address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external returns (uint poolAmountIn); function totalSupply() external view returns (uint); function balanceOf(address whom) external view returns (uint); function allowance(address src, address dst) external view returns (uint); function approve(address dst, uint amt) external returns (bool); function transfer(address dst, uint amt) external returns (bool); function transferFrom( address src, address dst, uint amt ) external returns (bool); function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) external returns (uint spotPrice); function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) external returns (uint tokenAmountOut); function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) external returns (uint tokenAmountIn); function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) external returns (uint poolAmountOut); function calcSingleInGivenPoolOut( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint poolAmountOut, uint swapFee ) external returns (uint tokenAmountIn); function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) external returns (uint tokenAmountOut); function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee ) external returns (uint poolAmountIn); } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IWETH.sol"; import './interfaces/IERC20Snapshot.sol'; import './interfaces/ITreasury.sol'; import './interfaces/IVault.sol'; import './interfaces/IMasset.sol'; import './interfaces/IDvd.sol'; import './interfaces/ISDvd.sol'; import './interfaces/IPool.sol'; import './interfaces/IBPool.sol'; import './utils/MathUtils.sol'; /// @title Lord of Coin /// @notice Lord of Coin finds the money, for you - to spend it. /// @author Lord Nami // Special thanks to TRIB as inspiration. // Special thanks to Lord Nami mods @AspieJames, @defimoon, @tectumor, @downsin, @ghost, @LordFes, @converge, @cryptycreepy, @cryptpower, @jonsnow // and everyone else who support this project by spreading the words on social media. contract LordOfCoin is ReentrancyGuard { using SafeMath for uint256; using MathUtils for uint256; using SafeERC20 for IERC20; event Bought(address indexed sender, address indexed recipient, uint256 musdAmount, uint256 dvdReceived); event Sold(address indexed sender, address indexed recipient, uint256 dvdAmount, uint256 musdReceived); event SoldToETH(address indexed sender, address indexed recipient, uint256 dvdAmount, uint256 ethReceived); event DividendClaimed(address indexed recipient, uint256 musdReceived); event DividendClaimedETH(address indexed recipient, uint256 ethReceived); event Received(address indexed from, uint256 amount); /// @notice Applied to every buy or sale of DVD. /// @dev Tax denominator uint256 public constant CURVE_TAX_DENOMINATOR = 10; /// @notice Applied to every buy of DVD before bonding curve tax. /// @dev Tax denominator uint256 public constant BUY_TAX_DENOMINATOR = 20; /// @notice Applied to every sale of DVD after bonding curve tax. /// @dev Tax denominator uint256 public constant SELL_TAX_DENOMINATOR = 10; /// @notice The slope of the bonding curve. uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals) /// @notice Address in which DVD are sent to be burned. /// These DVD can't be redeemed by the reserve. address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev WETH token address address weth; /// @dev Balancer pool WETH-MUSD address balancerPool; /// @dev mUSD token mStable address. address musd; /// @notice Dvd token instance. address public dvd; /// @notice SDvd token instance. address public sdvd; /// @notice Pair address for SDVD-ETH on uniswap address public sdvdEthPairAddress; /// @notice SDVD-ETH farming pool. address public sdvdEthPool; /// @notice DVD farming pool. address public dvdPool; /// @notice Dev treasury. address public devTreasury; /// @notice Pool treasury. address public poolTreasury; /// @notice Trading treasury. address public tradingTreasury; /// @notice Total dividend earned since the contract deployment. uint256 public totalDividendClaimed; /// @notice Total reserve value that backs all DVD in circulation. /// @dev Area below the bonding curve. uint256 public totalReserve; /// @notice Interface for integration with mStable. address public vault; /// @notice Current state of the application. /// Either already open (true) or not yet (false). bool public isMarketOpen = false; /// @notice Market will be open on this timestamp uint256 public marketOpenTime; /// @notice Current snapshot id /// Can be thought as week index, since snapshot is increased per week uint256 public snapshotId; /// @notice Snapshot timestamp. uint256 public snapshotTime; /// @notice Snapshot duration. uint256 public SNAPSHOT_DURATION = 1 weeks; /// @dev Total profits on each snapshot id. mapping(uint256 => uint256) private _totalProfitSnapshots; /// @dev Dividend paying SDVD supply on each snapshot id. mapping(uint256 => uint256) private _dividendPayingSDVDSupplySnapshots; /// @dev Flag to determine if account has claim their dividend on each snapshot id. mapping(address => mapping(uint256 => bool)) private _isDividendClaimedSnapshots; receive() external payable { emit Received(msg.sender, msg.value); } constructor( address _vault, address _uniswapRouter, address _balancerPool, address _dvd, address _sdvd, address _sdvdEthPool, address _dvdPool, address _devTreasury, address _poolTreasury, address _tradingTreasury, uint256 _marketOpenTime ) public { // Set vault vault = _vault; // mUSD instance musd = IVault(vault).musd(); // Approve vault to manage mUSD in this contract _approveMax(musd, vault); // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set balancer pool balancerPool = _balancerPool; // Set weth address weth = uniswapRouter.WETH(); // Approve balancer pool to manage mUSD in this contract _approveMax(musd, balancerPool); // Approve balancer pool to manage WETH in this contract _approveMax(weth, balancerPool); // Approve self to spend mUSD in this contract (used to buy from ETH / sell to ETH) _approveMax(musd, address(this)); dvd = _dvd; sdvd = _sdvd; sdvdEthPool = _sdvdEthPool; dvdPool = _dvdPool; devTreasury = _devTreasury; poolTreasury = _poolTreasury; tradingTreasury = _tradingTreasury; // Create SDVD ETH pair sdvdEthPairAddress = IUniswapV2Factory(uniswapRouter.factory()).createPair(sdvd, weth); // Set open time marketOpenTime = _marketOpenTime; // Set initial snapshot timestamp snapshotTime = _marketOpenTime; } /* ========== Modifier ========== */ modifier marketOpen() { require(isMarketOpen, 'Market not open'); _; } modifier onlyTradingTreasury() { require(msg.sender == tradingTreasury, 'Only treasury'); _; } /* ========== Trading Treasury Only ========== */ /// @notice Deposit trading profit to vault function depositTradingProfit(uint256 amount) external onlyTradingTreasury { // Deposit mUSD to vault IVault(vault).deposit(amount); } /* ========== Mutative ========== */ /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param musdAmount mUSD amount to be exchanged. function buy(uint256 musdAmount) external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(msg.sender, msg.sender, musdAmount); } /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param recipient Recipient of DVD token. /// @param musdAmount mUSD amount to be exchanged. function buyTo(address recipient, uint256 musdAmount) external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(msg.sender, recipient, musdAmount); } /// @notice Exchanges ETH to DVD. function buyFromETH() payable external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(address(this), msg.sender, _swapETHToMUSD(address(this), msg.value)); } /// @notice Exchanges DVD to mUSD. /// @param dvdAmount DVD amount to be exchanged. function sell(uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _sell(msg.sender, msg.sender, dvdAmount); } /// @notice Exchanges DVD to mUSD. /// @param recipient Recipient of mUSD. /// @param dvdAmount DVD amount to be exchanged. function sellTo(address recipient, uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _sell(msg.sender, recipient, dvdAmount); } /// @notice Exchanges DVD to ETH. /// @param dvdAmount DVD amount to be exchanged. function sellToETH(uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedETH, uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { // Sell DVD and receive mUSD in this contract (returnedMUSD, marketTax, curveTax, taxedDVD) = _sell(msg.sender, address(this), dvdAmount); // Swap received mUSD dividend for ether and send it back to sender returnedETH = _swapMUSDToETH(msg.sender, returnedMUSD); emit SoldToETH(msg.sender, msg.sender, dvdAmount, returnedETH); } /// @notice Claim dividend in mUSD. function claimDividend() external nonReentrant marketOpen returns (uint256 dividend) { return _claimDividend(msg.sender, msg.sender); } /// @notice Claim dividend in mUSD. /// @param recipient Recipient of mUSD. function claimDividendTo(address recipient) external nonReentrant marketOpen returns (uint256 dividend) { return _claimDividend(msg.sender, recipient); } /// @notice Claim dividend in ETH. function claimDividendETH() external nonReentrant marketOpen returns (uint256 dividend, uint256 receivedETH) { // Claim dividend to this contract dividend = _claimDividend(msg.sender, address(this)); // Swap received mUSD dividend for ether and send it back to sender receivedETH = _swapMUSDToETH(msg.sender, dividend); emit DividendClaimedETH(msg.sender, receivedETH); } /// @notice Check if we need to create new snapshot. function checkSnapshot() public { if (isMarketOpen) { // If time has passed for 1 week since last snapshot // and market is open if (snapshotTime.add(SNAPSHOT_DURATION) <= block.timestamp) { // Update snapshot timestamp snapshotTime = block.timestamp; // Take new snapshot snapshotId = ISDvd(sdvd).snapshot(); // Save the interest _totalProfitSnapshots[snapshotId] = totalProfit(); // Save dividend paying supply _dividendPayingSDVDSupplySnapshots[snapshotId] = dividendPayingSDVDSupply(); } // If something wrong / there is no interest, lets try again. if (snapshotId > 0 && _totalProfitSnapshots[snapshotId] == 0) { _totalProfitSnapshots[snapshotId] = totalProfit(); } } } /// @notice Release treasury. function releaseTreasury() public { if (isMarketOpen) { ITreasury(devTreasury).release(); ITreasury(poolTreasury).release(); ITreasury(tradingTreasury).release(); } } /* ========== View ========== */ /// @notice Get claimable dividend for address. /// @param account Account address. /// @return dividend Dividend in mUSD. function claimableDividend(address account) public view returns (uint256 dividend) { // If there is no snapshot or already claimed if (snapshotId == 0 || isDividendClaimedAt(account, snapshotId)) { return 0; } // Get sdvd balance at snapshot uint256 sdvdBalance = IERC20Snapshot(sdvd).balanceOfAt(account, snapshotId); if (sdvdBalance == 0) { return 0; } // Get dividend in mUSD based on SDVD balance dividend = sdvdBalance .mul(claimableProfitAt(snapshotId)) .div(dividendPayingSDVDSupplyAt(snapshotId)); } /// @notice Total mUSD that is now forever locked in the protocol. function totalLockedReserve() external view returns (uint256) { return _calculateReserveFromSupply(dvdBurnedAmount()); } /// @notice Total claimable profit. /// @return Total claimable profit in mUSD. function claimableProfit() public view returns (uint256) { return totalProfit().div(2); } /// @notice Total claimable profit in snapshot. /// @return Total claimable profit in mUSD. function claimableProfitAt(uint256 _snapshotId) public view returns (uint256) { return totalProfitAt(_snapshotId).div(2); } /// @notice Total profit. /// @return Total profit in MUSD. function totalProfit() public view returns (uint256) { uint256 vaultBalance = IVault(vault).getBalance(); // Sometimes mStable returns a value lower than the // deposit because their exchange rate gets updated after the deposit. if (vaultBalance < totalReserve) { vaultBalance = totalReserve; } return vaultBalance.sub(totalReserve); } /// @notice Total profit in snapshot. /// @param _snapshotId Snapshot id. /// @return Total profit in MUSD. function totalProfitAt(uint256 _snapshotId) public view returns (uint256) { return _totalProfitSnapshots[_snapshotId]; } /// @notice Check if dividend already claimed by account. /// @return Is dividend claimed. function isDividendClaimedAt(address account, uint256 _snapshotId) public view returns (bool) { return _isDividendClaimedSnapshots[account][_snapshotId]; } /// @notice Total supply of DVD. This includes burned DVD. /// @return Total supply of DVD in wei. function dvdTotalSupply() public view returns (uint256) { return IERC20(dvd).totalSupply(); } /// @notice Total DVD that have been burned. /// @dev These DVD are still in circulation therefore they /// are still considered on the bonding curve formula. /// @return Total burned DVD in wei. function dvdBurnedAmount() public view returns (uint256) { return IERC20(dvd).balanceOf(BURN_ADDRESS); } /// @notice DVD price in wei according to the bonding curve formula. /// @return Current DVD price in wei. function dvdPrice() external view returns (uint256) { // price = supply * multiplier return dvdTotalSupply().roundedDiv(DIVIDER); } /// @notice DVD price floor in wei according to the bonding curve formula. /// @return Current DVD price floor in wei. function dvdPriceFloor() external view returns (uint256) { return dvdBurnedAmount().roundedDiv(DIVIDER); } /// @notice Total supply of Dividend-paying SDVD. /// @return Total supply of SDVD in wei. function dividendPayingSDVDSupply() public view returns (uint256) { // Get total supply return IERC20(sdvd).totalSupply() // Get sdvd in uniswap pair balance .sub(IERC20(sdvd).balanceOf(sdvdEthPairAddress)) // Get sdvd in SDVD-ETH pool .sub(IERC20(sdvd).balanceOf(sdvdEthPool)) // Get sdvd in DVD pool .sub(IERC20(sdvd).balanceOf(dvdPool)) // Get sdvd in pool treasury .sub(IERC20(sdvd).balanceOf(poolTreasury)) // Get sdvd in dev treasury .sub(IERC20(sdvd).balanceOf(devTreasury)) // Get sdvd in trading treasury .sub(IERC20(sdvd).balanceOf(tradingTreasury)); } /// @notice Total supply of Dividend-paying SDVD in snapshot. /// @return Total supply of SDVD in wei. function dividendPayingSDVDSupplyAt(uint256 _snapshotId) public view returns (uint256) { return _dividendPayingSDVDSupplySnapshots[_snapshotId]; } /// @notice Calculates the amount of DVD in exchange for reserve after applying bonding curve tax. /// @param reserveAmount Reserve value in wei to use in the conversion. /// @return Token amount in wei after the 10% tax has been applied. function reserveToDVDTaxed(uint256 reserveAmount) external view returns (uint256) { if (reserveAmount == 0) { return 0; } uint256 tax = reserveAmount.div(CURVE_TAX_DENOMINATOR); uint256 totalDVD = reserveToDVD(reserveAmount); uint256 taxedDVD = reserveToDVD(tax); return totalDVD.sub(taxedDVD); } /// @notice Calculates the amount of reserve in exchange for DVD after applying bonding curve tax. /// @param tokenAmount Token value in wei to use in the conversion. /// @return Reserve amount in wei after the 10% tax has been applied. function dvdToReserveTaxed(uint256 tokenAmount) external view returns (uint256) { if (tokenAmount == 0) { return 0; } uint256 reserveAmount = dvdToReserve(tokenAmount); uint256 tax = reserveAmount.div(CURVE_TAX_DENOMINATOR); return reserveAmount.sub(tax); } /// @notice Calculates the amount of DVD in exchange for reserve. /// @param reserveAmount Reserve value in wei to use in the conversion. /// @return Token amount in wei. function reserveToDVD(uint256 reserveAmount) public view returns (uint256) { return _calculateReserveToDVD(reserveAmount, totalReserve, dvdTotalSupply()); } /// @notice Calculates the amount of reserve in exchange for DVD. /// @param tokenAmount Token value in wei to use in the conversion. /// @return Reserve amount in wei. function dvdToReserve(uint256 tokenAmount) public view returns (uint256) { return _calculateDVDToReserve(tokenAmount, dvdTotalSupply(), totalReserve); } /* ========== Internal ========== */ /// @notice Check if market can be opened function _checkOpenMarket() internal { require(marketOpenTime <= block.timestamp, 'Market not open'); if (!isMarketOpen) { // Set flag isMarketOpen = true; } } /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param sender Address that has mUSD token. /// @param recipient Address that will receive DVD token. /// @param musdAmount mUSD amount to be exchanged. function _buy(address sender, address recipient, uint256 musdAmount) internal returns (uint256 returnedDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { _checkOpenMarket(); checkSnapshot(); releaseTreasury(); require(musdAmount > 0, 'Cannot buy 0'); // Tax to be included as profit marketTax = musdAmount.div(BUY_TAX_DENOMINATOR); // Get amount after market tax uint256 inAmount = musdAmount.sub(marketTax); // Calculate bonding curve tax in mUSD curveTax = inAmount.div(CURVE_TAX_DENOMINATOR); // Convert mUSD amount to DVD amount uint256 totalDVD = reserveToDVD(inAmount); // Convert tax to DVD amount taxedDVD = reserveToDVD(curveTax); // Calculate DVD for recipient returnedDVD = totalDVD.sub(taxedDVD); // Transfer mUSD from sender to this contract IERC20(musd).safeTransferFrom(sender, address(this), musdAmount); // Deposit mUSD to vault IVault(vault).deposit(musdAmount); // Increase mUSD total reserve totalReserve = totalReserve.add(inAmount); // Send taxed DVD to burn address IDvd(dvd).mint(BURN_ADDRESS, taxedDVD); // Increase recipient DVD balance IDvd(dvd).mint(recipient, returnedDVD); // Increase user DVD Shareholder point IDvd(dvd).increaseShareholderPoint(recipient, returnedDVD); emit Bought(sender, recipient, musdAmount, returnedDVD); } /// @notice Exchanges DVD to mUSD. /// @param sender Address that has DVD token. /// @param recipient Address that will receive mUSD token. /// @param dvdAmount DVD amount to be exchanged. function _sell(address sender, address recipient, uint256 dvdAmount) internal returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { checkSnapshot(); releaseTreasury(); require(dvdAmount <= IERC20(dvd).balanceOf(sender), 'Insufficient balance'); require(dvdAmount > 0, 'Cannot sell 0'); require(IDvd(dvd).shareholderPointOf(sender) >= dvdAmount, 'Insufficient shareholder points'); // Convert number of DVD amount that user want to sell to mUSD amount uint256 reserveAmount = dvdToReserve(dvdAmount); // Calculate tax in mUSD curveTax = reserveAmount.div(CURVE_TAX_DENOMINATOR); // Make sure fee is enough require(curveTax >= 1, 'Insufficient tax'); // Get net amount uint256 net = reserveAmount.sub(curveTax); // Calculate taxed DVD taxedDVD = _calculateReserveToDVD( curveTax, totalReserve.sub(reserveAmount), dvdTotalSupply().sub(dvdAmount) ); // Tax to be included as profit marketTax = net.div(SELL_TAX_DENOMINATOR); // Get musd amount for recipient returnedMUSD = net.sub(marketTax); // Decrease total reserve totalReserve = totalReserve.sub(net); // Reduce user DVD balance IDvd(dvd).burn(sender, dvdAmount); // Send taxed DVD to burn address IDvd(dvd).mint(BURN_ADDRESS, taxedDVD); // Decrease sender DVD Shareholder point IDvd(dvd).decreaseShareholderPoint(sender, dvdAmount); // Redeem mUSD from vault IVault(vault).redeem(returnedMUSD); // Send mUSD to recipient IERC20(musd).safeTransfer(recipient, returnedMUSD); emit Sold(sender, recipient, dvdAmount, returnedMUSD); } /// @notice Claim dividend in mUSD. /// @param sender Address that has SDVD token. /// @param recipient Address that will receive mUSD dividend. function _claimDividend(address sender, address recipient) internal returns (uint256 dividend) { checkSnapshot(); releaseTreasury(); // Get dividend in mUSD based on SDVD balance dividend = claimableDividend(sender); require(dividend > 0, 'No dividend'); // Set dividend as claimed _isDividendClaimedSnapshots[sender][snapshotId] = true; // Redeem mUSD from vault IVault(vault).redeem(dividend); // Send dividend mUSD to user IERC20(musd).safeTransfer(recipient, dividend); emit DividendClaimed(recipient, dividend); } /// @notice Swap ETH to mUSD in this contract. /// @param amount ETH amount. /// @return musdAmount returned mUSD amount. function _swapETHToMUSD(address recipient, uint256 amount) internal returns (uint256 musdAmount) { // Convert ETH to WETH IWETH(weth).deposit{ value: amount }(); // Swap WETH to mUSD (musdAmount,) = IBPool(balancerPool).swapExactAmountIn(weth, amount, musd, 0, uint256(-1)); // Send mUSD if (recipient != address(this)) { IERC20(musd).safeTransfer(recipient, musdAmount); } } /// @notice Swap mUSD to ETH in this contract. /// @param amount mUSD Amount. /// @return ethAmount returned ETH amount. function _swapMUSDToETH(address recipient, uint256 amount) internal returns (uint256 ethAmount) { // Swap mUSD to WETH (ethAmount,) = IBPool(balancerPool).swapExactAmountIn(musd, amount, weth, 0, uint256(-1)); // Convert WETH to ETH IWETH(weth).withdraw(ethAmount); // Send ETH if (recipient != address(this)) { payable(recipient).transfer(ethAmount); } } /// @notice Approve maximum value to spender function _approveMax(address tkn, address spender) internal { uint256 max = uint256(- 1); IERC20(tkn).safeApprove(spender, max); } /** * Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve: * p = m * s * The reserve equals to the area below the bonding curve * r = s^2 / 2 * The formula for the supply becomes * s = sqrt(2 * r / m) * * In solidity computations, we are using divider instead of multiplier (because its an integer). * All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in * multiplications and divisions */ /// @notice Computes the increased supply given an amount of reserve. /// @param _reserveDelta The amount of reserve in wei to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @return _supplyDelta token amount in wei. function _calculateReserveToDVD( uint256 _reserveDelta, uint256 _totalReserve, uint256 _supply ) internal pure returns (uint256 _supplyDelta) { uint256 _reserve = _totalReserve; uint256 _newReserve = _reserve.add(_reserveDelta); // s = sqrt(2 * r / m) uint256 _newSupply = MathUtils.sqrt( _newReserve .mul(2) .mul(DIVIDER) // inverse the operation (Divider instead of multiplier) .mul(1e18) // compensation for the squared unit ); _supplyDelta = _newSupply.sub(_supply); } /// @notice Computes the decrease in reserve given an amount of DVD. /// @param _supplyDelta The amount of DVD in wei to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @return _reserveDelta Reserve amount in wei. function _calculateDVDToReserve( uint256 _supplyDelta, uint256 _supply, uint256 _totalReserve ) internal pure returns (uint256 _reserveDelta) { require(_supplyDelta <= _supply, 'Token amount must be less than the supply'); uint256 _newSupply = _supply.sub(_supplyDelta); uint256 _newReserve = _calculateReserveFromSupply(_newSupply); _reserveDelta = _totalReserve.sub(_newReserve); } /// @notice Calculates reserve given a specific supply. /// @param _supply The token supply in wei to be used in the calculation. /// @return _reserve Reserve amount in wei. function _calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256 _reserve) { // r = s^2 * m / 2 _reserve = _supply .mul(_supply) .div(DIVIDER) // inverse the operation (Divider instead of multiplier) .div(2) .roundedDiv(1e18); // correction of the squared unit } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IERC20Snapshot { function balanceOfAt(address account, uint256 snapshotId) external view returns (uint256); function totalSupplyAt(uint256 snapshotId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface ITreasury { function release() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IVault { function savingsContract() external view returns (address); function musd() external view returns (address); function deposit(uint256) external; function redeem(uint256) external; function getBalance() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { MassetStructs } from "./MassetStructs.sol"; /// /// @title IMasset /// @dev (Internal) Interface for interacting with Masset /// VERSION: 1.0 /// DATE: 2020-05-05 interface IMasset is MassetStructs { /// @dev Calc interest function collectInterest() external returns (uint256 massetMinted, uint256 newTotalSupply); /// @dev Minting function mint(address _basset, uint256 _bassetQuantity) external returns (uint256 massetMinted); function mintTo(address _basset, uint256 _bassetQuantity, address _recipient) external returns (uint256 massetMinted); function mintMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantity, address _recipient) external returns (uint256 massetMinted); /// @dev Swapping function swap( address _input, address _output, uint256 _quantity, address _recipient) external returns (uint256 output); function getSwapOutput( address _input, address _output, uint256 _quantity) external view returns (bool, string memory, uint256 output); /// @dev Redeeming function redeem(address _basset, uint256 _bassetQuantity) external returns (uint256 massetRedeemed); function redeemTo(address _basset, uint256 _bassetQuantity, address _recipient) external returns (uint256 massetRedeemed); function redeemMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantities, address _recipient) external returns (uint256 massetRedeemed); function redeemMasset(uint256 _mAssetQuantity, address _recipient) external; /// @dev Setters for the Manager or Gov to update module info function upgradeForgeValidator(address _newForgeValidator) external; /// @dev Setters for Gov to set system params function setSwapFee(uint256 _swapFee) external; /// @dev Getters function getBasketManager() external view returns(address); function forgeValidator() external view returns (address); function totalSupply() external view returns (uint256); function swapFee() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IDvd is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function increaseShareholderPoint(address account, uint256 amount) external; function decreaseShareholderPoint(address account, uint256 amount) external; function shareholderPointOf(address account) external view returns (uint256); function totalShareholderPoint() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface ISDvd is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function setMinter(address account, bool value) external; function setNoFeeAddress(address account, bool value) external; function setPairAddress(address _pairAddress) external; function snapshot() external returns (uint256); function syncPairTokenTotalSupply() external returns (bool isPairTokenBurned); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IPool { function openFarm() external; function distributeBonusRewards(uint256 amount) external; function stake(uint256 amount) external; function stakeTo(address recipient, uint256 amount) external; function withdraw(uint256 amount) external; function withdrawTo(address recipient, uint256 amount) external; function claimReward() external; function claimRewardTo(address recipient) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.7.0; import '@openzeppelin/contracts/math/SafeMath.sol'; library MathUtils { using SafeMath for uint256; /// @notice Calculates the square root of a given value. 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; } // else z = 0 } /// @notice Rounds a division result. function roundedDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'div by 0'); uint256 halfB = (b.mod(2) == 0) ? (b.div(2)) : (b.div(2).add(1)); return (a.mod(b) >= halfB) ? (a.div(b).add(1)) : (a.div(b)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // // @title MassetStructs // @author Stability Labs Pty. Ltd. // @notice Structs used in the Masset contract and associated Libs interface MassetStructs { // Stores high level basket info struct Basket { // Array of Bassets currently active Basset[] bassets; // Max number of bAssets that can be present in any Basket uint8 maxBassets; // Some bAsset is undergoing re-collateralisation bool undergoingRecol; // // In the event that we do not raise enough funds from the auctioning of a failed Basset, // The Basket is deemed as failed, and is undercollateralised to a certain degree. // The collateralisation ratio is used to calc Masset burn rate. bool failed; uint256 collateralisationRatio; } // Stores bAsset info. The struct takes 5 storage slots per Basset struct Basset { // Address of the bAsset address addr; // Status of the basset, BassetStatus status; // takes uint8 datatype (1 byte) in storage // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool isTransferFeeCharged; // takes a byte in storage // // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint256 ratio; // Target weights of the Basset (100% == 1e18) uint256 maxWeight; // Amount of the Basset that is held in Collateral uint256 vaultBalance; } // Status of the Basset - has it broken its peg? enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } // Internal details on Basset struct BassetDetails { Basset bAsset; address integrator; uint8 index; } // All details needed to Forge with multiple bAssets struct ForgePropsMulti { bool isValid; // Flag to signify that forge bAssets have passed validity check Basset[] bAssets; address[] integrators; uint8[] indexes; } // All details needed for proportionate Redemption struct RedeemPropsMulti { uint256 colRatio; Basset[] bAssets; address[] integrators; uint8[] indexes; } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import './MathUtils.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; library LordLib { using SafeMath for uint256; using MathUtils for uint256; /// @notice The slope of the bonding curve. uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals) /** * Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve: * p = m * s * The reserve equals to the area below the bonding curve * r = s^2 / 2 * The formula for the supply becomes * s = sqrt(2 * r / m) * * In solidity computations, we are using divider instead of multiplier (because its an integer). * All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in * multiplications and divisions */ /// @notice Computes the increased supply given an amount of reserve. /// @param _reserveDelta The amount of reserve in wei to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @return token amount in wei. function calculateReserveToTokens( uint256 _reserveDelta, uint256 _totalReserve, uint256 _supply ) internal pure returns (uint256) { uint256 _reserve = _totalReserve; uint256 _newReserve = _reserve.add(_reserveDelta); // s = sqrt(2 * r / m) uint256 _newSupply = MathUtils.sqrt( _newReserve .mul(2) .mul(DIVIDER) // inverse the operation (Divider instead of multiplier) .mul(1e18) // compensation for the squared unit ); uint256 _supplyDelta = _newSupply.sub(_supply); return _supplyDelta; } /// @notice Computes the decrease in reserve given an amount of tokens. /// @param _supplyDelta The amount of tokens in wei to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @return Reserve amount in wei. function calculateTokensToReserve( uint256 _supplyDelta, uint256 _supply, uint256 _totalReserve ) internal pure returns (uint256) { require(_supplyDelta <= _supply, 'Token amount must be less than the supply'); uint256 _newSupply = _supply.sub(_supplyDelta); uint256 _newReserve = calculateReserveFromSupply(_newSupply); uint256 _reserveDelta = _totalReserve.sub(_newReserve); return _reserveDelta; } /// @notice Calculates reserve given a specific supply. /// @param _supply The token supply in wei to be used in the calculation. /// @return Reserve amount in wei. function calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256) { // r = s^2 * m / 2 uint256 _reserve = _supply .mul(_supply) .div(DIVIDER) // inverse the operation (Divider instead of multiplier) .div(2); return _reserve.roundedDiv(1e18); // correction of the squared unit } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import './interfaces/IVault.sol'; import './interfaces/IMStable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract Vault is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event FundMigration(uint256 value); /// @notice mStable governance proxy contract. /// It should not change. address public nexusGovernance; /// @notice mStable savingsContract contract. /// It can be changed through governance. address public savingsContract; /// @notice mUSD address. address public musd; /// @notice LoC address address public controller; constructor(address _musd, address _nexus) public { // Set mUSD address musd = _musd; // Set nexus governance address nexusGovernance = _nexus; // Get mStable savings contract savingsContract = _fetchMStableSavings(); // Approve savings contract to spend mUSD on this contract _approveMax(musd, savingsContract); } /* ========== Modifiers ========== */ modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately. function init(address _controller) external onlyOwner { // Set Lord of coin controller = _controller; // Renounce ownership immediately after init renounceOwnership(); } /* ========== Controller Only ========== */ /// @notice Deposits reserve into savingsAccount. /// @dev It is part of Vault's interface. /// @param amount Value to be deposited. function deposit(uint256 amount) external onlyController { require(amount > 0, 'Cannot deposit 0'); // Transfer mUSD from sender to this contract IERC20(musd).safeTransferFrom(msg.sender, address(this), amount); // Send to savings account IMStable(savingsContract).depositSavings(amount); } /// @notice Redeems reserve from savingsAccount. /// @dev It is part of Vault's interface. /// @param amount Value to be redeemed. function redeem(uint256 amount) external onlyController { require(amount > 0, 'Cannot redeem 0'); // Redeem the amount in credits uint256 credited = IMStable(savingsContract).redeem(_getRedeemInput(amount)); // Send credited amount to sender IERC20(musd).safeTransfer(msg.sender, credited); } /* ========== View ========== */ /// @notice Returns balance in reserve from the savings contract. /// @dev It is part of Vault's interface. /// @return balance Reserve amount in the savings contract. function getBalance() public view returns (uint256 balance) { // Get balance in credits amount balance = IMStable(savingsContract).creditBalances(address(this)); // Convert credits to reserve amount if (balance > 0) { balance = balance.mul(IMStable(savingsContract).exchangeRate()).div(1e18); } } /* ========== Mutative ========== */ /// @notice Allows anyone to migrate all reserve to new savings contract. /// @dev Only use if the savingsContract has been changed by governance. function migrateSavings() external { address currentSavingsContract = _fetchMStableSavings(); require(currentSavingsContract != savingsContract, 'Already on latest contract'); _swapSavingsContract(); } /* ========== Internal ========== */ /// @notice Convert amount to mStable credits amount for redeem. function _getRedeemInput(uint256 amount) internal view returns (uint256 credits) { // Add 1 because the amounts always round down // e.g. i have 51 credits, e4 10 = 20.4 // to withdraw 20 i need 20*10/4 = 50 + 1 credits = amount.mul(1e18).div(IMStable(savingsContract).exchangeRate()).add(1); } /// @notice Approve spender to max. function _approveMax(address token, address spender) internal { uint256 max = uint256(- 1); IERC20(token).safeApprove(spender, max); } /// @notice Gets the current mStable Savings Contract address. /// @return address of mStable Savings Contract. function _fetchMStableSavings() internal view returns (address) { address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager')); return IMStable(manager).savingsContracts(musd); } /// @notice Worker function that swaps the reserve to a new savings contract. function _swapSavingsContract() internal { // Get all savings balance uint256 balance = getBalance(); // Redeem the amount in credits uint256 credited = IMStable(savingsContract).redeem(_getRedeemInput(balance)); // Get new savings contract savingsContract = _fetchMStableSavings(); // Approve new savings contract as mUSD spender _approveMax(musd, savingsContract); // Send to new savings account IMStable(savingsContract).depositSavings(credited); // Emit event emit FundMigration(balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IMStable { // Nexus function getModule(bytes32) external view returns (address); // Savings Manager function savingsContracts(address) external view returns (address); // Savings Contract function exchangeRate() external view returns (uint256); function creditBalances(address) external view returns (uint256); function depositSavings(uint256) external; function redeem(uint256) external returns (uint256); function depositInterest(uint256) external; } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/ITreasury.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract SDvd is ERC20Snapshot, Ownable { using SafeMath for uint256; /// @notice Minter address. DVD-ETH Pool, DVD Pool. mapping(address => bool) public minters; /// @dev No fee address. SDVD-ETH Pool, DVD Pool. mapping(address => bool) public noFeeAddresses; /// @notice Lord of Coin address public controller; address public devTreasury; address public poolTreasury; address public tradingTreasury; /// @dev SDVD-ETH pair address address public pairAddress; /// @dev SDVD-ETH pair token IUniswapV2Pair pairToken; /// @dev Used to check LP removal uint256 lastPairTokenTotalSupply; constructor() public ERC20('Stock dvd.finance', 'SDVD') { } /* ========== Modifiers ========== */ modifier onlyMinter { require(minters[msg.sender], 'Minter only'); _; } modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init( address _controller, address _pairAddress, address _sdvdEthPool, address _dvdPool, address _devTreasury, address _poolTreasury, address _tradingTreasury ) external onlyOwner { controller = _controller; // Create uniswap pair for SDVD-ETH pool pairAddress = _pairAddress; // Set pair token pairToken = IUniswapV2Pair(pairAddress); devTreasury = _devTreasury; poolTreasury = _poolTreasury; tradingTreasury = _tradingTreasury; // Add pools as SDVD minter _setMinter(_sdvdEthPool, true); _setMinter(_dvdPool, true); // Add no fees address _setNoFeeAddress(_sdvdEthPool, true); _setNoFeeAddress(_dvdPool, true); _setNoFeeAddress(devTreasury, true); _setNoFeeAddress(poolTreasury, true); _setNoFeeAddress(tradingTreasury, true); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Minter Only ========== */ function mint(address account, uint256 amount) external onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) external onlyMinter { _burn(account, amount); } /* ========== Controller Only ========== */ function snapshot() external onlyController returns (uint256) { return _snapshot(); } /* ========== Public ========== */ function syncPairTokenTotalSupply() public returns (bool isPairTokenBurned) { // Get LP token total supply uint256 pairTokenTotalSupply = pairToken.totalSupply(); // If last total supply > current total supply, // It means LP token is burned by uniswap, which means someone removing liquidity isPairTokenBurned = lastPairTokenTotalSupply > pairTokenTotalSupply; // Save total supply lastPairTokenTotalSupply = pairTokenTotalSupply; } /* ========== Internal ========== */ function _setMinter(address account, bool value) internal { minters[account] = value; } function _setNoFeeAddress(address account, bool value) internal { noFeeAddresses[account] = value; } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { // Check uniswap liquidity removal _checkUniswapLiquidityRemoval(sender); if (noFeeAddresses[sender] || noFeeAddresses[recipient]) { super._transfer(sender, recipient, amount); } else { // 0.5% for dev uint256 devFee = amount.div(200); // 1% for farmers in pool uint256 poolFee = devFee.mul(2); // 1% to goes as sharing profit uint256 tradingFee = poolFee; // Get net amount uint256 net = amount .sub(devFee) .sub(poolFee) .sub(tradingFee); super._transfer(sender, recipient, net); super._transfer(sender, devTreasury, devFee); super._transfer(sender, poolTreasury, poolFee); super._transfer(sender, tradingTreasury, tradingFee); } } function _checkUniswapLiquidityRemoval(address sender) internal { bool isPairTokenBurned = syncPairTokenTotalSupply(); // If from uniswap LP address if (sender == pairAddress) { // Check if liquidity removed require(isPairTokenBurned == false, 'LP removal disabled'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // SPDX-License-Identifier: Unlicensed 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/IDvd.sol"; import "./interfaces/ISDvd.sol"; import "./interfaces/ITreasury.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. abstract contract Pool is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Staked(address indexed sender, address indexed recipient, uint256 amount); event Withdrawn(address indexed sender, address indexed recipient, uint256 amount); event Claimed(address indexed sender, address indexed recipient, uint256 net, uint256 tax, uint256 total); event Halving(uint256 amount); /// @dev Token will be DVD or SDVD-ETH UNI-V2 address public stakedToken; ISDvd public sdvd; /// @notice Flag to determine if farm is open bool public isFarmOpen = false; /// @notice Farming will be open on this timestamp uint256 public farmOpenTime; uint256 public rewardAllocation; uint256 public rewardRate; uint256 public rewardDuration = 1460 days; // halving per 4 years uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public finishTime; uint256 public bonusRewardAllocation; uint256 public bonusRewardRate; uint256 public bonusRewardDuration = 1 days; // Reward bonus distributed every day, must be the same value with pool treasury release threshold uint256 public bonusLastUpdateTime; uint256 public bonusRewardPerTokenStored; uint256 public bonusRewardFinishTime; struct AccountInfo { // Staked token balance uint256 balance; // Normal farming reward uint256 reward; uint256 rewardPerTokenPaid; // Bonus reward from transaction fee uint256 bonusReward; uint256 bonusRewardPerTokenPaid; } /// @dev Account info mapping(address => AccountInfo) public accountInfos; /// @dev Total supply of staked tokens uint256 private _totalSupply; /// @notice Total rewards minted from this pool uint256 public totalRewardMinted; // @dev Lord of Coin address controller; // @dev Pool treasury address poolTreasury; constructor(address _poolTreasury, uint256 _farmOpenTime) public { poolTreasury = _poolTreasury; farmOpenTime = _farmOpenTime; } /* ========== Modifiers ========== */ modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } modifier onlyPoolTreasury { require(msg.sender == poolTreasury, 'Treasury only'); _; } modifier farmOpen { require(isFarmOpen, 'Farm not open'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _controller, address _stakedToken) external onlyOwner { controller = _controller; stakedToken = _stakedToken; sdvd = ISDvd(ILordOfCoin(_controller).sdvd()); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Pool Treasury Only ========== */ /// @notice Distribute bonus rewards to farmers /// @dev Can only be called by pool treasury function distributeBonusRewards(uint256 amount) external onlyPoolTreasury { // Set bonus reward allocation bonusRewardAllocation = amount; // Calculate bonus reward rate bonusRewardRate = bonusRewardAllocation.div(bonusRewardDuration); // Set finish time bonusRewardFinishTime = block.timestamp.add(bonusRewardDuration); // Set last update time bonusLastUpdateTime = block.timestamp; } /* ========== Mutative ========== */ /// @notice Stake token. /// @dev Need to approve staked token first. /// @param amount Token amount. function stake(uint256 amount) external nonReentrant { _stake(msg.sender, msg.sender, amount); } /// @notice Stake token. /// @dev Need to approve staked token first. /// @param recipient Address who receive staked token balance. /// @param amount Token amount. function stakeTo(address recipient, uint256 amount) external nonReentrant { _stake(msg.sender, recipient, amount); } /// @notice Withdraw token. /// @param amount Token amount. function withdraw(uint256 amount) external nonReentrant farmOpen { _withdraw(msg.sender, msg.sender, amount); } /// @notice Withdraw token. /// @param recipient Address who receive staked token. /// @param amount Token amount. function withdrawTo(address recipient, uint256 amount) external nonReentrant farmOpen { _withdraw(msg.sender, recipient, amount); } /// @notice Claim SDVD reward /// @return Reward net amount /// @return Reward tax amount /// @return Total Reward amount function claimReward() external nonReentrant farmOpen returns(uint256, uint256, uint256) { return _claimReward(msg.sender, msg.sender); } /// @notice Claim SDVD reward /// @param recipient Address who receive reward. /// @return Reward net amount /// @return Reward tax amount /// @return Total Reward amount function claimRewardTo(address recipient) external nonReentrant farmOpen returns(uint256, uint256, uint256) { return _claimReward(msg.sender, recipient); } /* ========== Internal ========== */ function _updateReward(address account) internal { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { accountInfos[account].reward = earned(account); accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored; } } function _updateBonusReward(address account) internal { bonusRewardPerTokenStored = bonusRewardPerToken(); bonusLastUpdateTime = lastTimeBonusRewardApplicable(); if (account != address(0)) { accountInfos[account].bonusReward = bonusEarned(account); accountInfos[account].bonusRewardPerTokenPaid = bonusRewardPerTokenStored; } } /// @notice Stake staked token /// @param sender address. Address who have the token. /// @param recipient address. Address who receive staked token balance. function _stake(address sender, address recipient, uint256 amount) internal virtual { _checkOpenFarm(); _checkHalving(); _updateReward(recipient); _updateBonusReward(recipient); _notifyController(); require(amount > 0, 'Cannot stake 0'); IERC20(stakedToken).safeTransferFrom(sender, address(this), amount); _totalSupply = _totalSupply.add(amount); accountInfos[recipient].balance = accountInfos[recipient].balance.add(amount); emit Staked(sender, recipient, amount); } /// @notice Withdraw staked token /// @param sender address. Address who have stake the token. /// @param recipient address. Address who receive the staked token. function _withdraw(address sender, address recipient, uint256 amount) internal virtual { _checkHalving(); _updateReward(sender); _updateBonusReward(sender); _notifyController(); require(amount > 0, 'Cannot withdraw 0'); require(accountInfos[sender].balance >= amount, 'Insufficient balance'); _totalSupply = _totalSupply.sub(amount); accountInfos[sender].balance = accountInfos[sender].balance.sub(amount); IERC20(stakedToken).safeTransfer(recipient, amount); emit Withdrawn(sender, recipient, amount); } /// @notice Claim reward /// @param sender address. Address who have stake the token. /// @param recipient address. Address who receive the reward. /// @return totalNetReward Total net SDVD reward. /// @return totalTaxReward Total taxed SDVD reward. /// @return totalReward Total SDVD reward. function _claimReward(address sender, address recipient) internal virtual returns(uint256 totalNetReward, uint256 totalTaxReward, uint256 totalReward) { _checkHalving(); _updateReward(sender); _updateBonusReward(sender); _notifyController(); uint256 reward = accountInfos[sender].reward; uint256 bonusReward = accountInfos[sender].bonusReward; totalReward = reward.add(bonusReward); require(totalReward > 0, 'No reward to claim'); if (reward > 0) { // Reduce reward first accountInfos[sender].reward = 0; // Apply tax uint256 tax = reward.div(claimRewardTaxDenominator()); uint256 net = reward.sub(tax); // Mint SDVD as reward to recipient sdvd.mint(recipient, net); // Mint SDVD tax to pool treasury sdvd.mint(address(poolTreasury), tax); // Increase total totalNetReward = totalNetReward.add(net); totalTaxReward = totalTaxReward.add(tax); // Set stats totalRewardMinted = totalRewardMinted.add(reward); } if (bonusReward > 0) { // Reduce bonus reward first accountInfos[sender].bonusReward = 0; // Get balance and check so we doesn't overrun uint256 balance = sdvd.balanceOf(address(this)); if (bonusReward > balance) { bonusReward = balance; } // Apply tax uint256 tax = bonusReward.div(claimRewardTaxDenominator()); uint256 net = bonusReward.sub(tax); // Send bonus reward to recipient IERC20(sdvd).safeTransfer(recipient, net); // Send tax to treasury IERC20(sdvd).safeTransfer(address(poolTreasury), tax); // Increase total totalNetReward = totalNetReward.add(net); totalTaxReward = totalTaxReward.add(tax); } if (totalReward > 0) { emit Claimed(sender, recipient, totalNetReward, totalTaxReward, totalReward); } } /// @notice Check if farm can be open function _checkOpenFarm() internal { require(farmOpenTime <= block.timestamp, 'Farm not open'); if (!isFarmOpen) { // Set flag isFarmOpen = true; // Initialize lastUpdateTime = block.timestamp; finishTime = block.timestamp.add(rewardDuration); rewardRate = rewardAllocation.div(rewardDuration); // Initialize bonus bonusLastUpdateTime = block.timestamp; bonusRewardFinishTime = block.timestamp.add(bonusRewardDuration); bonusRewardRate = bonusRewardAllocation.div(bonusRewardDuration); } } /// @notice Check and do halving when finish time reached function _checkHalving() internal { if (block.timestamp >= finishTime) { // Halving reward rewardAllocation = rewardAllocation.div(2); // Calculate reward rate rewardRate = rewardAllocation.div(rewardDuration); // Set finish time finishTime = block.timestamp.add(rewardDuration); // Set last update time lastUpdateTime = block.timestamp; // Emit event emit Halving(rewardAllocation); } } /// @notice Check if need to increase snapshot in lord of coin function _notifyController() internal { ILordOfCoin(controller).checkSnapshot(); ILordOfCoin(controller).releaseTreasury(); } /* ========== View ========== */ /// @notice Get staked token total supply function totalSupply() external view returns (uint256) { return _totalSupply; } /// @notice Get staked token balance function balanceOf(address account) external view returns (uint256) { return accountInfos[account].balance; } /// @notice Get full earned amount and bonus /// @dev Combine earned function fullEarned(address account) external view returns (uint256) { return earned(account).add(bonusEarned(account)); } /// @notice Get full reward rate /// @dev Combine reward rate function fullRewardRate() external view returns (uint256) { return rewardRate.add(bonusRewardRate); } /// @notice Get claim reward tax function claimRewardTaxDenominator() public view returns (uint256) { if (block.timestamp < farmOpenTime.add(365 days)) { // 50% tax return 2; } else if (block.timestamp < farmOpenTime.add(730 days)) { // 33% tax return 3; } else if (block.timestamp < farmOpenTime.add(1095 days)) { // 25% tax return 4; } else if (block.timestamp < farmOpenTime.add(1460 days)) { // 20% tax return 5; } else { // 10% tax return 10; } } /// Normal rewards function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, finishTime); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return accountInfos[account].balance.mul( rewardPerToken().sub(accountInfos[account].rewardPerTokenPaid) ) .div(1e18) .add(accountInfos[account].reward); } /// Bonus function lastTimeBonusRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, bonusRewardFinishTime); } function bonusRewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return bonusRewardPerTokenStored; } return bonusRewardPerTokenStored.add( lastTimeBonusRewardApplicable().sub(bonusLastUpdateTime).mul(bonusRewardRate).mul(1e18).div(_totalSupply) ); } function bonusEarned(address account) public view returns (uint256) { return accountInfos[account].balance.mul( bonusRewardPerToken().sub(accountInfos[account].bonusRewardPerTokenPaid) ) .div(1e18) .add(accountInfos[account].bonusReward); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./interfaces/IDvd.sol"; import "./Pool.sol"; contract SDvdEthPool is Pool { event StakedETH(address indexed account, uint256 amount); event ClaimedAndStaked(address indexed account, uint256 amount); /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @notice LGE state bool public isLGEActive = true; /// @notice Max initial deposit cap uint256 public LGE_INITIAL_DEPOSIT_CAP = 5 ether; /// @notice Amount in SDVD. After hard cap reached, stake ETH will function as normal staking. uint256 public LGE_HARD_CAP = 200 ether; /// @dev Initial price multiplier uint256 public LGE_INITIAL_PRICE_MULTIPLIER = 2; constructor(address _poolTreasury, address _uniswapRouter, uint256 _farmOpenTime) public Pool(_poolTreasury, _farmOpenTime) { rewardAllocation = 240000 * 1e18; rewardAllocation = rewardAllocation.sub(LGE_HARD_CAP.div(2)); uniswapRouter = IUniswapV2Router02(_uniswapRouter); uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); weth = uniswapRouter.WETH(); } /// @dev Added to receive ETH when swapping on Uniswap receive() external payable { } /// @notice Stake token using ETH conveniently. function stakeETH() external payable nonReentrant { _stakeETH(msg.value); } /// @notice Stake token using SDVD and ETH conveniently. /// @dev User must approve SDVD first function stakeSDVD(uint256 amountToken) external payable nonReentrant farmOpen { require(isLGEActive == false, 'LGE still active'); uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); uint256 amountETH = amountToken.mul(pairETHBalance).div(pairSDVDBalance); // Make sure received eth is enough require(msg.value >= amountETH, 'Not enough ETH'); // Check if there is excess eth uint256 excessETH = msg.value.sub(amountETH); // Send back excess eth if (excessETH > 0) { msg.sender.transfer(excessETH); } // Transfer sdvd from sender to this contract IERC20(sdvd).safeTransferFrom(msg.sender, address(this), amountToken); // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountToken); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountToken, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); } /// @notice Claim reward and re-stake conveniently. function claimRewardAndStake() external nonReentrant farmOpen { require(isLGEActive == false, 'LGE still active'); // Claim SDVD reward to this address (uint256 totalNetReward,,) = _claimReward(msg.sender, address(this)); // Split total reward to be swapped uint256 swapAmountSDVD = totalNetReward.div(2); // Swap path address[] memory path = new address[](2); path[0] = address(sdvd); path[1] = weth; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(address(uniswapRouter), swapAmountSDVD); // Swap SDVD to ETH // Param: uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactTokensForETH(swapAmountSDVD, 0, path, address(this), block.timestamp.add(30 minutes)); // Get received ETH amount from swap uint256 amountETHReceived = amounts[1]; // Get pair address and balance uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); // Get available SDVD uint256 amountSDVD = totalNetReward.sub(swapAmountSDVD); // Calculate how much ETH needed to provide liquidity uint256 amountETH = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // If required ETH amount to add liquidity is bigger than what we have // Then we need to reduce SDVD amount if (amountETH > amountETHReceived) { // Set ETH amount amountETH = amountETHReceived; // Get amount SDVD needed to add liquidity uint256 amountSDVDRequired = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // Send dust if (amountSDVD > amountSDVDRequired) { IERC20(sdvd).safeTransfer(msg.sender, amountSDVD.sub(amountSDVDRequired)); } // Set SDVD amount amountSDVD = amountSDVDRequired; } // Else if we have too much ETH else if (amountETHReceived > amountETH) { // Send excess msg.sender.transfer(amountETHReceived.sub(amountETH)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); emit ClaimedAndStaked(msg.sender, liquidity); } /* ========== Internal ========== */ /// @notice Stake ETH /// @param value Value in ETH function _stakeETH(uint256 value) internal { // If in LGE if (isLGEActive) { // SDVD-ETH pair address uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); if (pairSDVDBalance == 0) { require(msg.value <= LGE_INITIAL_DEPOSIT_CAP, 'Initial deposit cap reached'); } uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); uint256 amountETH = msg.value; // If SDVD balance = 0 then set initial price uint256 amountSDVD = pairSDVDBalance == 0 ? amountETH.mul(LGE_INITIAL_PRICE_MULTIPLIER) : amountETH.mul(pairSDVDBalance).div(pairETHBalance); uint256 excessETH = 0; // If amount token to be minted pass the hard cap if (pairSDVDBalance.add(amountSDVD) > LGE_HARD_CAP) { // Get excess token uint256 excessToken = pairSDVDBalance.add(amountSDVD).sub(LGE_HARD_CAP); // Reduce it amountSDVD = amountSDVD.sub(excessToken); // Get excess ether excessETH = excessToken.mul(pairETHBalance).div(pairSDVDBalance); // Reduce amount ETH to be put on uniswap liquidity amountETH = amountETH.sub(excessETH); } // Mint LGE SDVD ISDvd(sdvd).mint(address(this), amountSDVD); // Add liquidity in uniswap and send the LP token to this contract IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Recheck the SDVD in pair address pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); // Set LGE active state isLGEActive = pairSDVDBalance < LGE_HARD_CAP; // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); // If there is excess ETH if (excessETH > 0) { _stakeETH(excessETH); } } else { // Split ETH sent uint256 amountETH = value.div(2); // Swap path address[] memory path = new address[](2); path[0] = weth; path[1] = address(sdvd); // Swap ETH to SDVD using uniswap // Param: uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactETHForTokens{value : amountETH}( 0, path, address(this), block.timestamp.add(30 minutes) ); // Get SDVD amount uint256 amountSDVDReceived = amounts[1]; // Get pair address balance uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); // Get available ETH amountETH = value.sub(amountETH); // Calculate amount of SDVD needed to add liquidity uint256 amountSDVD = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // If required SDVD amount to add liquidity is bigger than what we have // Then we need to reduce ETH amount if (amountSDVD > amountSDVDReceived) { // Set SDVD amount amountSDVD = amountSDVDReceived; // Get amount ETH needed to add liquidity uint256 amountETHRequired = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // Send dust back to sender if (amountETH > amountETHRequired) { msg.sender.transfer(amountETH.sub(amountETHRequired)); } // Set ETH amount amountETH = amountETHRequired; } // Else if we have too much SDVD else if (amountSDVDReceived > amountSDVD) { // Send dust IERC20(sdvd).transfer(msg.sender, amountSDVDReceived.sub(amountSDVD)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Sync total token supply ISDvd(sdvd).syncPairTokenTotalSupply(); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); } emit StakedETH(msg.sender, msg.value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IERC20Mock is IERC20 { function mint(address account, uint256 amount) external; function mockMint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function mockBurn(address account, uint256 amount) external; } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./interfaces/IPool.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract PoolTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @dev SDVD ETH pool address address public sdvdEthPool; /// @dev DVD pool address address public dvdPool; /// @dev SDVD contract address address public sdvd; /// @dev Distribute reward every 1 day to pool uint256 public releaseThreshold = 1 days; /// @dev Last release timestamp uint256 public releaseTime; /// @notice Swap reward distribution numerator when this time reached uint256 public numeratorSwapTime; /// @notice How long we should wait before swap numerator uint256 public NUMERATOR_SWAP_WAIT = 4383 days; // 12 normal years + 3 leap days; constructor(address _sdvd) public { sdvd = _sdvd; releaseTime = block.timestamp; numeratorSwapTime = block.timestamp.add(NUMERATOR_SWAP_WAIT); } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _sdvdEthPool, address _dvdPool) external onlyOwner { sdvdEthPool = _sdvdEthPool; dvdPool = _dvdPool; // Renounce ownership after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release pool treasury to pool and give rewards for farmers. function release() external { _release(); } /* ========== Internal ========== */ /// @notice Release pool treasury to pool function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Check balance uint256 balance = IERC20(sdvd).balanceOf(address(this)); // If there is balance if (balance > 0) { // Get numerator uint256 numerator = block.timestamp <= numeratorSwapTime ? 4 : 6; // Distribute reward to pools uint dvdPoolReward = balance.div(10).mul(numerator); IERC20(sdvd).transfer(dvdPool, dvdPoolReward); IPool(dvdPool).distributeBonusRewards(dvdPoolReward); uint256 sdvdEthPoolReward = balance.sub(dvdPoolReward); IERC20(sdvd).transfer(sdvdEthPool, sdvdEthPoolReward); IPool(sdvdEthPool).distributeBonusRewards(sdvdEthPoolReward); } } } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./interfaces/IDvd.sol"; import "./interfaces/IPool.sol"; import "./Pool.sol"; contract DvdPool is Pool { event StakedETH(address indexed account, uint256 amount); event WithdrawnETH(address indexed account, uint256 amount); event ClaimedAndStaked(address indexed account, uint256 amount); /// @dev mUSD instance address public musd; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @dev SDVD ETH pool address address public sdvdEthPool; constructor(address _poolTreasury, address _musd, address _uniswapRouter, address _sdvdEthPool, uint256 _farmOpenTime) public Pool(_poolTreasury, _farmOpenTime) { rewardAllocation = 360000 * 1e18; musd = _musd; uniswapRouter = IUniswapV2Router02(_uniswapRouter); uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); weth = uniswapRouter.WETH(); sdvdEthPool = _sdvdEthPool; } /// @dev Added to receive ETH when swapping on Uniswap receive() external payable { } /// @notice Stake token using ETH conveniently. function stakeETH() external payable nonReentrant { // Buy DVD using ETH (uint256 dvdAmount,,,) = ILordOfCoin(controller).buyFromETH{value : msg.value}(); // Approve self IERC20(stakedToken).approve(address(this), dvdAmount); // Stake user DVD _stake(address(this), msg.sender, dvdAmount); emit StakedETH(msg.sender, msg.value); } /// @notice Withdraw token to ETH conveniently. /// @param amount Number of staked DVD token. /// @dev Need to approve DVD token first. function withdrawETH(uint256 amount) external nonReentrant farmOpen { // Call withdraw to this address _withdraw(msg.sender, address(this), amount); // Approve LoC to spend DVD IERC20(stakedToken).approve(controller, amount); // Sell received DVD to ETH (uint256 receivedETH,,,,) = ILordOfCoin(controller).sellToETH(amount); // Send received ETH to sender msg.sender.transfer(receivedETH); emit WithdrawnETH(msg.sender, receivedETH); } /// @notice Claim reward and re-stake conveniently. function claimRewardAndStake() external nonReentrant farmOpen { // Claim SDVD reward to this address (uint256 totalNetReward,,) = _claimReward(msg.sender, address(this)); // Split total reward to be swapped uint256 swapAmountSDVD = totalNetReward.div(2); // Swap path address[] memory path = new address[](2); path[0] = address(sdvd); path[1] = weth; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(address(uniswapRouter), swapAmountSDVD); // Swap SDVD to ETH // Param: uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactTokensForETH(swapAmountSDVD, 0, path, address(this), block.timestamp.add(30 minutes)); // Get received ETH amount from swap uint256 amountETHReceived = amounts[1]; // Get pair address and balance address pairAddress = uniswapFactory.getPair(address(sdvd), weth); uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(pairAddress); uint256 pairETHBalance = IERC20(weth).balanceOf(pairAddress); // Get available SDVD uint256 amountSDVD = totalNetReward.sub(swapAmountSDVD); // Calculate how much ETH needed to provide liquidity uint256 amountETH = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // If required ETH amount to add liquidity is bigger than what we have // Then we need to reduce SDVD amount if (amountETH > amountETHReceived) { // Set ETH amount amountETH = amountETHReceived; // Get amount SDVD needed to add liquidity uint256 amountSDVDRequired = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // Send dust if (amountSDVD > amountSDVDRequired) { IERC20(sdvd).safeTransfer(msg.sender, amountSDVD.sub(amountSDVDRequired)); } // Set SDVD amount amountSDVD = amountSDVDRequired; } // Else if we have too much ETH else if (amountETHReceived > amountETH) { // Send dust msg.sender.transfer(amountETHReceived.sub(amountETH)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve SDVD ETH pool to spend LP token IERC20(pairAddress).approve(sdvdEthPool, liquidity); // Stake LP token for sender IPool(sdvdEthPool).stakeTo(msg.sender, liquidity); emit ClaimedAndStaked(msg.sender, liquidity); } /* ========== Internal ========== */ /// @notice Override stake function to check shareholder points /// @param amount Number of DVD token to be staked. function _stake(address sender, address recipient, uint256 amount) internal virtual override { require(IDvd(stakedToken).shareholderPointOf(sender) >= amount, 'Insufficient shareholder points'); super._stake(sender, recipient, amount); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/math/Math.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import './DvdShareholderPoint.sol'; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract Dvd is ERC20, DvdShareholderPoint, Ownable { /// @notice Minter for DVD token. This value will be Lord of Coin address. address public minter; /// @notice Controller. This value will be Lord of Coin address. address public controller; /// @dev DVD pool address. address public dvdPool; constructor() public ERC20('Dvd.finance', 'DVD') { } /* ========== Modifiers ========== */ modifier onlyMinter { require(msg.sender == minter, 'Minter only'); _; } modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _controller, address _dvdPool) external onlyOwner { controller = _controller; minter = _controller; dvdPool = _dvdPool; // Renounce ownership immediately after init renounceOwnership(); } /* ========== Minter Only ========== */ function mint(address account, uint256 amount) external onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) external onlyMinter { _burn(account, amount); } /* ========== Controller Only ========== */ /// @notice Increase shareholder point. /// @dev Can only be called by the LoC contract. /// @param account Account address /// @param amount The amount to increase. function increaseShareholderPoint(address account, uint256 amount) external onlyController { _increaseShareholderPoint(account, amount); } /// @notice Decrease shareholder point. /// @dev Can only be called by the LoC contract. /// @param account Account address /// @param amount The amount to decrease. function decreaseShareholderPoint(address account, uint256 amount) external onlyController { _decreaseShareholderPoint(account, amount); } /* ========== Internal ========== */ /// @notice ERC20 Before token transfer hook function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); // If transfer between two accounts if (from != address(0) && to != address(0)) { // Remove shareholder point from account _decreaseShareholderPoint(from, Math.min(amount, shareholderPointOf(from))); } // If transfer is from DVD pool (This occurs when user withdraw their stake, or using convenient stake ETH) // Give back their shareholder point. if (from == dvdPool) { _increaseShareholderPoint(to, amount); } } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; abstract contract DvdShareholderPoint { using SafeMath for uint256; event ShareholderPointIncreased(address indexed account, uint256 amount, uint256 totalShareholderPoint); event ShareholderPointDecreased(address indexed account, uint256 amount, uint256 totalShareholderPoint); /// @dev Our shareholder point tracker /// Shareholder point will determine how much token one account can use to farm SDVD /// This point can only be increased/decreased by LoC buy/sell function to prevent people trading DVD on exchange and don't pay their taxes mapping(address => uint256) private _shareholderPoints; uint256 private _totalShareholderPoint; /// @notice Get shareholder point of an account /// @param account address. function shareholderPointOf(address account) public view returns (uint256) { return _shareholderPoints[account]; } /// @notice Get total shareholder points function totalShareholderPoint() public view returns (uint256) { return _totalShareholderPoint; } /// @notice Increase shareholder point /// @param amount The amount to increase. function _increaseShareholderPoint(address account, uint256 amount) internal { // If account is burn address then skip if (account != address(0)) { _totalShareholderPoint = _totalShareholderPoint.add(amount); _shareholderPoints[account] = _shareholderPoints[account].add(amount); emit ShareholderPointIncreased(account, amount, _shareholderPoints[account]); } } /// @notice Decrease shareholder point. /// @param amount The amount to decrease. function _decreaseShareholderPoint(address account, uint256 amount) internal { // If account is burn address then skip if (account != address(0)) { _totalShareholderPoint = _totalShareholderPoint.sub(amount); _shareholderPoints[account] = _shareholderPoints[account] > amount ? _shareholderPoints[account].sub(amount) : 0; emit ShareholderPointDecreased(account, amount, _shareholderPoints[account]); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.7.0; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; /** * @title StableMath * @author Stability Labs Pty. Ltd. * @notice A library providing safe mathematical operations to multiply and * divide with standardised precision. * @dev Derives from OpenZeppelin's SafeMath lib and uses generic system * wide variables for managing precision. */ library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * @dev bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x.mul(FULL_SCALE); } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return c Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x.mul(ratio); // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled.add(RATIO_SCALE.sub(1)); // return 100..00.999e8 / 1e8 = 1e18 return ceil.div(RATIO_SCALE); } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return c Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 uint256 y = x.mul(RATIO_SCALE); // return 1e22 / 1e12 = 1e10 return y.div(ratio); } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } }
Gets the current mStable Savings Contract address. return address of mStable Savings Contract.
function _fetchMStableSavings() internal view returns (address) { address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager')); return IMStable(manager).savingsContracts(musd); }
1,609,427
./full_match/4/0x1DDdB15f9e9734Af0B974968098c0a7f3437a49b/sources/contracts/periphery/LyraMarketsRegistry.sol
Method to register the addresses of a new deployments market optionMarket Address of the optionMarket contract liquidityPool Address of the liquidityPool contract liquidityCertificate Address of the liquidityCertificate contract optionGreekCache Address of the optionGreekCache contract optionMarketPricer Address of the optionMarketPricer contract poolHedger Address of the poolHedger contract shortCollateral Address of the shortCollateral contract quoteAsset Address of quote asset baseAsset Address of base asset optionToken Address of optionToken contract/
function addMarket( address optionMarket, address liquidityPool, address liquidityCertificate, address optionGreekCache, address optionMarketPricer, address poolHedger, address shortCollateral, address quoteAsset, address baseAsset, address optionToken ) external onlyOwner { require(optionMarkets.add(optionMarket), "market already present"); optionMarketsAddresses[optionMarket] = MarketAddresses( liquidityPool, liquidityCertificate, optionGreekCache, optionMarketPricer, poolHedger, shortCollateral, quoteAsset, baseAsset, optionToken ); emit MarketAdded( optionMarket, liquidityPool, liquidityCertificate, optionGreekCache, optionMarketPricer, poolHedger, shortCollateral, quoteAsset, baseAsset, optionToken ); }
702,419
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../utils/EnumerableSet.sol'; import '../utils/Address.sol'; import '../utils/Context.sol'; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require( hasRole(_roles[role].adminRole, _msgSender()), 'AccessControl: sender must be an admin to grant' ); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require( hasRole(_roles[role].adminRole, _msgSender()), 'AccessControl: sender must be an admin to revoke' ); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require( account == _msgSender(), 'AccessControl: can only renounce roles for self' ); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; interface IERC1155 { /****************************************| | Events | |_______________________________________*/ /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount ); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts ); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /****************************************| | Functions | |_______________________________________*/ /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data ) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; interface IERC1155Metadata { event URI(string _uri, uint256 indexed _id); /****************************************| | Functions | |_______________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) external view returns (string memory); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received( address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data ) external returns (bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external returns (bytes4); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import '../../utils/SafeMath.sol'; import '../../interfaces/IERC1155TokenReceiver.sol'; import '../../interfaces/IERC1155.sol'; import '../../utils/Address.sol'; import '../../utils/ERC165.sol'; /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC1155, ERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping(address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping(address => mapping(address => bool)) internal operators; /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) public virtual override { require( (msg.sender == _from) || isApprovedForAll(_from, msg.sender), 'ERC1155#safeTransferFrom: INVALID_OPERATOR' ); require(_to != address(0), 'ERC1155#safeTransferFrom: INVALID_RECIPIENT'); // require(_amount <= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) public virtual override { // Requirements require( (msg.sender == _from) || isApprovedForAll(_from, msg.sender), 'ERC1155#safeBatchTransferFrom: INVALID_OPERATOR' ); require( _to != address(0), 'ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT' ); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount ) internal { _beforeTokenTransfer(msg.sender, _from, _to, _id, _amount, ''); // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received( address _from, address _to, uint256 _id, uint256 _amount, uint256 _gasLimit, bytes memory _data ) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received{ gas: _gasLimit }(msg.sender, _from, _id, _amount, _data); require( retval == ERC1155_RECEIVED_VALUE, 'ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE' ); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts ) internal { require( _ids.length == _amounts.length, 'ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH' ); _beforeBatchTokenTransfer(msg.sender, _from, _to, _ids, _amounts, ''); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data ) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{ gas: _gasLimit }(msg.sender, _from, _ids, _amounts, _data); require( retval == ERC1155_BATCH_RECEIVED_VALUE, 'ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE' ); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) public virtual override { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public view virtual override returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public view override returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view override returns (uint256[] memory) { require( _owners.length == _ids.length, 'ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH' ); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | HOOKS | |__________________________________*/ /** * @notice overrideable hook for single transfers. */ function _beforeTokenTransfer( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) internal virtual {} /** * @notice overrideable hook for batch transfers. */ function _beforeBatchTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual {} /***********************************| | ERC165 Functions | |__________________________________*/ /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public pure virtual override returns (bool) { if (_interfaceID == type(IERC1155).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../../interfaces/IERC1155TokenReceiver.sol'; import '../../utils/ERC165.sol'; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC165, IERC1155TokenReceiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } function supportsInterface(bytes4 _interfaceID) public pure virtual override returns (bool) { if (_interfaceID == type(IERC1155TokenReceiver).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import '../../interfaces/IERC1155Metadata.sol'; import '../../utils/ERC165.sol'; /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata is IERC1155Metadata, ERC165 { // URI's default URI prefix string private _baseMetadataURI; // contract metadata URL string private _contractMetadataURI; // Hex numbers for creating hexadecimal tokenId bytes16 private constant HEX_MAP = '0123456789ABCDEF'; // bytes4(keccak256('contractURI()')) == 0xe8a3d485 bytes4 private constant _INTERFACE_ID_CONTRACT_URI = 0xe8a3d485; /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * @return URI string */ function uri(uint256 _id) public view virtual override returns (string memory) { return _uri(_baseMetadataURI, _id, 0); } /** * @notice Opensea calls this fuction to get information about how to display storefront. * * @return full URI to the location of the contract metadata. */ function contractURI() public view returns (string memory) { return _contractMetadataURI; } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_uri(_baseMetadataURI, _tokenIDs[i], 0), _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory newBaseMetadataURI) internal { _baseMetadataURI = newBaseMetadataURI; } /** * @notice Will update the contract metadata URI * @param newContractMetadataURI New contract metadata URI */ function _setContractMetadataURI(string memory newContractMetadataURI) internal { _contractMetadataURI = newContractMetadataURI; } /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` or CONTRACT_URI */ function supportsInterface(bytes4 _interfaceID) public pure virtual override returns (bool) { if ( _interfaceID == type(IERC1155Metadata).interfaceId || _interfaceID == _INTERFACE_ID_CONTRACT_URI ) { return true; } return super.supportsInterface(_interfaceID); } /***********************************| | Utility private Functions | |__________________________________*/ /** * @notice returns uri * @param tokenId Unsigned integer to convert to string */ function _uri( string memory base, uint256 tokenId, uint256 minLength ) internal view returns (string memory) { if (bytes(base).length == 0) base = _baseMetadataURI; // Calculate URI uint256 temp = tokenId; uint256 length = tokenId == 0 ? 2 : 0; while (temp != 0) { length += 2; temp >>= 8; } if (length > minLength) minLength = length; bytes memory buffer = new bytes(minLength); for (uint256 i = minLength; i > minLength - length; --i) { buffer[i - 1] = HEX_MAP[tokenId & 0xf]; tokenId >>= 4; } minLength -= length; while (minLength > 0) buffer[--minLength] = '0'; return string(abi.encodePacked(base, buffer, '.json')); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import './ERC1155.sol'; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { using SafeMath for uint256; /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint( address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal { _beforeTokenTransfer(msg.sender, address(0x0), _to, _id, _amount, _data); // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, gasleft(), _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { require( _ids.length == _amounts.length, 'ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH' ); _beforeBatchTokenTransfer( msg.sender, address(0x0), _to, _ids, _amounts, _data ); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived( address(0x0), _to, _ids, _amounts, gasleft(), _data ); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn( address _from, uint256 _id, uint256 _amount ) internal { _beforeTokenTransfer(msg.sender, _from, address(0x0), _id, _amount, ''); //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn( address _from, uint256[] memory _ids, uint256[] memory _amounts ) internal { // Number of mints to execute uint256 nBurn = _ids.length; require( nBurn == _amounts.length, 'ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH' ); _beforeBatchTokenTransfer( msg.sender, _from, address(0x0), _ids, _amounts, '' ); // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // SPDX-License-Identifier: MIT AND Apache-2.0 pragma solidity 0.7.6; /** * Utility library of inline functions on addresses */ library Address { // Default hash for EOA accounts returned by extcodehash bytes32 internal constant ACCOUNT_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract. * @param _address address of the account to check * @return Whether the target address is a contract */ function isContract(address _address) internal view returns (bool) { bytes32 codehash; // Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address or if it has a non-zero code hash or account hash // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(_address) } return (codehash != 0x0 && codehash != ACCOUNT_HASH); } /** * @dev Performs a Solidity function call using a low level `call`. * * 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. */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: No contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: No contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /* * @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: Apache-2.0 pragma solidity 0.7.6; abstract contract ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface(bytes4 _interfaceID) public pure virtual returns (bool) { return _interfaceID == this.supportsInterface.selector; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, 'EnumerableSet: index out of bounds'); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath#mul: OVERFLOW'); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'SafeMath#div: 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 Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'SafeMath#sub: UNDERFLOW'); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath#add: OVERFLOW'); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'SafeMath#mod: DIVISION_BY_ZERO'); return a % b; } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; import '../../0xerc1155/interfaces/IERC20.sol'; import '../../0xerc1155/tokens/ERC1155/ERC1155Holder.sol'; import '../token/interfaces/IWOWSCryptofolio.sol'; import '../token/interfaces/IWOWSERC1155.sol'; import '../utils/AddressBook.sol'; import '../utils/interfaces/IAddressRegistry.sol'; import '../utils/TokenIds.sol'; import './interfaces/ICFolioItemCallback.sol'; import './WOWSMinterPauser.sol'; abstract contract OpenSeaProxyRegistry { mapping(address => address) public proxies; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-1155[ERC1155] * Multi Token Standard, including the Metadata URI extension. * * This contract is an extension of the minter preset. It accepts the address * of the contract minting the token via the ERC-1155 data parameter. When * the token is transferred or burned, the minter is notified. * * Token ID allocation: * * - 32Bit Stock Cards * - 32Bit Custom Cards * - Remaining CFolio NFTs */ contract TradeFloor is WOWSMinterPauser, ERC1155Holder { using TokenIds for uint256; ////////////////////////////////////////////////////////////////////////////// // Roles ////////////////////////////////////////////////////////////////////////////// // Only OPERATORS can approve when trading is restricted bytes32 public constant OPERATOR_ROLE = 'OPERATOR_ROLE'; ////////////////////////////////////////////////////////////////////////////// // Constants ////////////////////////////////////////////////////////////////////////////// // solhint-disable-next-line const-name-snakecase string public constant name = 'Wolves of Wall Street - C-Folio NFTs'; // solhint-disable-next-line const-name-snakecase string public constant symbol = 'WOWSCFNFT'; ////////////////////////////////////////////////////////////////////////////// // Modifier ////////////////////////////////////////////////////////////////////////////// modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Only admin'); _; } modifier notNull(address adr) { require(adr != address(0), 'Null address'); _; } ////////////////////////////////////////////////////////////////////////////// // State ////////////////////////////////////////////////////////////////////////////// /** * @dev Per token information, used to cap NFT's and to allow querying a list * of NFT's owned by an address */ struct ListKey { uint256 index; } // Per token information struct TokenInfo { bool minted; // Make sure we only mint 1 ListKey listKey; // Next tokenId in the owner linkedList } // slither-disable-next-line uninitialized-state mapping(uint256 => TokenInfo) private _tokenInfos; // Mapping owner -> first owned token // // Note that we work 1 based here because of initialization // e.g. firstId == 1 links to tokenId 0; struct Owned { uint256 count; ListKey listKey; // First tokenId in linked list } // slither-disable-next-line uninitialized-state mapping(address => Owned) private _owned; // Our SFT contract, needed to check for locked transfers IWOWSERC1155 private immutable _sftHolder; // Migration!! This is the old sft contract IWOWSERC1155 private immutable _sftHolderOld; // Restrict approvals to OPERATOR_ROLE members bool private _tradingRestricted = false; ////////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////////// /** * @dev Emitted when the state of restriction has updated * * @param tradingRestricted True if trading has been restricted, false otherwise */ event RestrictionUpdated(bool tradingRestricted); ////////////////////////////////////////////////////////////////////////////// // OpenSea compatibility ////////////////////////////////////////////////////////////////////////////// // OpenSea per-account proxy registry. Used to whitelist Approvals and save // GAS. OpenSeaProxyRegistry private immutable _openSeaProxyRegistry; address private immutable _deployer; // OpenSea events event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); ////////////////////////////////////////////////////////////////////////////// // Rarible compatibility ////////////////////////////////////////////////////////////////////////////// /* * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * * => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584 */ bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584; uint256 private _fee; address private _feeRecipient; // Rarible events // solhint-disable-next-line event-name-camelcase event CreateERC1155_v1(address indexed creator, string name, string symbol); event SecondarySaleFees( uint256 tokenId, address payable[] recipients, uint256[] bps ); ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev Construct the contract * * @param addressRegistry Registry containing our system addresses * * Note: Pause operation in this context. Only calls from Proxy allowed. */ constructor( IAddressRegistry addressRegistry, OpenSeaProxyRegistry openSeaProxyRegistry, IWOWSERC1155 sftHolderOld ) { // Initialize {AccessControl} _setupRole( DEFAULT_ADMIN_ROLE, _getAddressRegistryAddress(addressRegistry, AddressBook.ADMIN_ACCOUNT) ); // Immutable, visible for all contexts _sftHolder = IWOWSERC1155( _getAddressRegistryAddress(addressRegistry, AddressBook.SFT_HOLDER_PROXY) ); _sftHolderOld = sftHolderOld; // Immutable, visible for all contexts _openSeaProxyRegistry = openSeaProxyRegistry; // Immutable, visible for all contexts _deployer = _getAddressRegistryAddress( addressRegistry, AddressBook.DEPLOYER ); // Pause this instance _pause(true); } /** * @dev One time contract initializer * * @param tokenUriPrefix The ERC-1155 metadata URI Prefix * @param contractUri The contract metadata URI */ function initialize( IAddressRegistry addressRegistry, string memory tokenUriPrefix, string memory contractUri ) public { // Validate state require(_feeRecipient == address(0), 'already initialized'); // Initialize {AccessControl} address admin = _getAddressRegistryAddress( addressRegistry, AddressBook.ADMIN_ACCOUNT ); _setupRole(DEFAULT_ADMIN_ROLE, admin); // Initialize {ERC1155Metadata} _setBaseMetadataURI(tokenUriPrefix); _setContractMetadataURI(contractUri); _feeRecipient = _getAddressRegistryAddress( addressRegistry, AddressBook.REWARD_HANDLER ); _fee = 1000; // 10% // This event initializes Rarible storefront emit CreateERC1155_v1(_deployer, name, symbol); // OpenSea enable storefront editing emit OwnershipTransferred(address(0), _deployer); } ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Return list of tokenIds owned by `account` */ function getTokenIds(address account) external view returns (uint256[] memory) { Owned storage list = _owned[account]; uint256[] memory result = new uint256[](list.count); ListKey storage key = list.listKey; for (uint256 i = 0; i < list.count; ++i) { result[i] = key.index; key = _tokenInfos[key.index].listKey; } return result; } ////////////////////////////////////////////////////////////////////////////// // Implementation of {IERC1155} via {WOWSMinterPauser} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, uint256 amount, bytes calldata data ) public override notNull(from) notNull(to) { // Call parent super.safeTransferFrom(from, to, tokenId, amount, data); uint256[] memory tokenIds = new uint256[](1); uint256[] memory amounts = new uint256[](1); tokenIds[0] = tokenId; amounts[0] = amount; _onTransfer(from, to, tokenIds, amounts); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) public override notNull(from) notNull(to) { // Validate parameters require(tokenIds.length == amounts.length, "Lengths don't match"); // Call parent super.safeBatchTransferFrom(from, to, tokenIds, amounts, data); _onTransfer(from, to, tokenIds, amounts); } /** * @dev See {IERC1155-setApprovalForAll}. * * Override setApprovalForAll to be able to restrict to known operators. */ function setApprovalForAll(address operator, bool approved) public virtual override { // Validate access require( !_tradingRestricted || hasRole(OPERATOR_ROLE, operator), 'forbidden' ); // Call ancestor super.setApprovalForAll(operator, approved); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { if (!_tradingRestricted && address(_openSeaProxyRegistry) != address(0)) { // Whitelist OpenSea proxy contract for easy trading. OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry( _openSeaProxyRegistry ); if (proxyRegistry.proxies(account) == operator) { return true; } } // Call ancestor return super.isApprovedForAll(account, operator); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {IERC1155MetadataURI} via {WOWSMinterPauser} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {IERC1155MetadataURI-uri}. * * Revert for unminted SFT NFTs. */ function uri(uint256 tokenId) public view override returns (string memory) { // Validate state require(_tokenInfos[tokenId].minted, 'Not minted'); // Load state return _uri('', tokenId, 0); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {WOWSMinterPauser} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ERC1155MintBurn-_burn}. */ function burn( address account, uint256 tokenId, uint256 amount ) public override notNull(account) { // Call ancestor super.burn(account, tokenId, amount); // Perform internal handling uint256[] memory tokenIds = new uint256[](1); uint256[] memory amounts = new uint256[](1); tokenIds[0] = tokenId; amounts[0] = amount; _onTransfer(account, address(0), tokenIds, amounts); } /** * @dev See {ERC1155MintBurn-_batchBurn}. */ function burnBatch( address account, uint256[] calldata tokenIds, uint256[] calldata amounts ) public virtual override notNull(account) { // Validate parameters require(tokenIds.length == amounts.length, "Lengths don't match"); // Call ancestor super.burnBatch(account, tokenIds, amounts); // Perform internal handling _onTransfer(account, address(0), tokenIds, amounts); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {IERC1155TokenReceiver} via {ERC1155Holder} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {IERC1155TokenReceiver-onERC1155Received} */ function onERC1155Received( address operator, address from, uint256 tokenId, uint256 amount, bytes calldata data ) public override returns (bytes4) { // Handle tokens uint256[] memory tokenIds = new uint256[](1); tokenIds[0] = tokenId; uint256[] memory amounts = new uint256[](1); amounts[0] = amount; _onTokensReceived(from, tokenIds, amounts, data); // Call ancestor return super.onERC1155Received(operator, from, tokenId, amount, data); } /** * @dev See {IERC1155TokenReceiver-onERC1155BatchReceived} */ function onERC1155BatchReceived( address operator, address from, uint256[] memory tokenIds, uint256[] memory amounts, bytes calldata data ) public override returns (bytes4) { // Handle tokens _onTokensReceived(from, tokenIds, amounts, data); // Call ancestor return super.onERC1155BatchReceived(operator, from, tokenIds, amounts, data); } ////////////////////////////////////////////////////////////////////////////// // Administrative functions ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ERC1155Metadata-setBaseMetadataURI}. */ function setBaseMetadataURI(string memory baseMetadataURI) external onlyAdmin { // Set state _setBaseMetadataURI(baseMetadataURI); } /** * @dev Set contract metadata URI */ function setContractMetadataURI(string memory newContractUri) public onlyAdmin { _setContractMetadataURI(newContractUri); } /** * @dev Register interfaces */ function supportsInterface(bytes4 _interfaceID) public pure virtual override(WOWSMinterPauser, ERC1155Holder) returns (bool) { // Register rarible fee interface if (_interfaceID == _INTERFACE_ID_FEES) { return true; } return super.supportsInterface(_interfaceID); } /** * @dev Withdraw tokenAddress ERC20token to destination * * A future improvement would be to swap the token into WOWS. * * @param tokenAddress the address of the token to transfer. Cannot be * rewardToken. */ function collectGarbage(address tokenAddress) external onlyAdmin { // Transfer token to msg.sender uint256 amountToken = IERC20(tokenAddress).balanceOf(address(this)); if (amountToken > 0) IERC20(tokenAddress).transfer(_msgSender(), amountToken); } /** * @dev Restrict trading to OPERATOR_ROLE (see setApprovalForAll) */ function restrictTrading(bool restrict) external onlyAdmin { // Update state _tradingRestricted = restrict; // Dispatch event emit RestrictionUpdated(restrict); } /** * @dev Self destruct implementation contract */ function destructContract(address payable newContract) external onlyAdmin { // slither-disable-next-line suicidal selfdestruct(newContract); } ////////////////////////////////////////////////////////////////////////////// // OpenSea compatibility ////////////////////////////////////////////////////////////////////////////// function isOwner() external view returns (bool) { return _msgSender() == owner(); } function owner() public view returns (address) { return _deployer; } ////////////////////////////////////////////////////////////////////////////// // Rarible fees and events ////////////////////////////////////////////////////////////////////////////// function setFee(uint256 fee) external onlyAdmin { // Update state _fee = fee; } function setFeeRecipient(address feeRecipient) external onlyAdmin { // Update state _feeRecipient = feeRecipient; } function getFeeRecipients(uint256) public view returns (address payable[] memory) { // Return value address payable[] memory recipients = new address payable[](1); // Load state recipients[0] = payable(_feeRecipient); return recipients; } function getFeeBps(uint256) public view returns (uint256[] memory) { // Return value uint256[] memory bps = new uint256[](1); // Load state bps[0] = _fee; return bps; } function logURI(uint256 tokenId) external { emit URI(uri(tokenId), tokenId); } ////////////////////////////////////////////////////////////////////////////// // Internal details ////////////////////////////////////////////////////////////////////////////// function _onTransfer( address from, address to, uint256[] memory tokenIds, uint256[] memory amounts ) private { // Count SFT tokenIds uint256 length = tokenIds.length; uint256 validLength = 0; // Relink owner for (uint256 i = 0; i < length; ++i) { if (amounts[i] == 1) { _relinkOwner(from, to, tokenIds[i], uint256(-1)); ++validLength; } // CryptoFolios send 0 amount!! else require(amounts[i] == 0, 'TF: Invalid amount'); } // On Burn we need to transfer SFT ownership back if (validLength > 0 && to == address(0)) { uint256[] memory sftTokenIds = new uint256[](validLength); uint256[] memory sftAmounts = new uint256[](validLength); validLength = 0; for (uint256 i = 0; i < length; ++i) { if (amounts[i] == 1) { uint256 tokenId = tokenIds[i]; sftTokenIds[validLength] = tokenId.toSftTokenId(); sftAmounts[validLength++] = 1; } } IWOWSERC1155 sftHolder = _sftHolder; // Migration!!! Remove if all TF's are on new contract if ( address(_sftHolderOld) != address(0) && _sftHolderOld.balanceOf(address(this), sftTokenIds[0]) == 1 ) sftHolder = _sftHolderOld; sftHolder.safeBatchTransferFrom( address(this), _msgSender(), sftTokenIds, sftAmounts, '' ); } } /** * @dev SFT token arrived, provide an NFT */ function _onTokensReceived( address from, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) private { // We only support tokens from our SFT Holder contract require(_msgSender() == address(_sftHolder), 'TF: Invalid sender'); // Validate parameters require(tokenIds.length == amounts.length, 'TF: Lengths mismatch'); // To save gas we allow minting directly into a given recipient address sftRecipient; if (data.length == 20) { sftRecipient = _getAddress(data); require(sftRecipient != address(0), 'TF: invalid recipient'); } else sftRecipient = from; // Update state uint256[] memory mintedTokenIds = new uint256[](tokenIds.length); for (uint256 i = 0; i < tokenIds.length; ++i) { require(amounts[i] == 1, 'Amount != 1 not allowed'); uint256 mintedTokenId = _hashedTokenId(tokenIds[i]); mintedTokenIds[i] = mintedTokenId; // OpenSea only listens to TransferSingle event on mint _mintAndEmit(sftRecipient, mintedTokenId); } _onTransfer(address(0), sftRecipient, mintedTokenIds, amounts); } /** * @dev Ownership change -> update linked list owner -> tokenId * * If tokenIdNew is != uint256(-1) this function executes an * ownership transfer of "from" from tokenId to tokenIdNew * In this case "to" must be set to 0. */ function _relinkOwner( address from, address to, uint256 tokenId, uint256 tokenIdNew ) internal { // Load state TokenInfo storage tokenInfo = _tokenInfos[tokenId]; // Remove tokenId from List if (from != address(0)) { // Load state Owned storage fromList = _owned[from]; // Validate state require(fromList.count > 0, 'Count mismatch'); ListKey storage key = fromList.listKey; uint256 count = fromList.count; // Search the token which links to tokenId for (; count > 0 && key.index != tokenId; --count) key = _tokenInfos[key.index].listKey; require(key.index == tokenId, 'Key mismatch'); if (tokenIdNew == uint256(-1)) { // Unlink prev -> tokenId key.index = tokenInfo.listKey.index; // Decrement count fromList.count--; } else { // replace tokenId -> tokenIdNew key.index = tokenIdNew; TokenInfo storage tokenInfoNew = _tokenInfos[tokenIdNew]; require(!tokenInfoNew.minted, 'Must not be minted'); tokenInfoNew.listKey.index = tokenInfo.listKey.index; tokenInfoNew.minted = true; } // Unlink tokenId -> next tokenInfo.listKey.index = 0; require(tokenInfo.minted, 'Must be minted'); tokenInfo.minted = false; } // Update state if (to != address(0)) { Owned storage toList = _owned[to]; tokenInfo.listKey.index = toList.listKey.index; require(!tokenInfo.minted, 'Must not be minted'); tokenInfo.minted = true; toList.listKey.index = tokenId; toList.count++; } } /** * @dev Get the address from the user data parameter * * @param data Per ERC-1155, the data parameter is additional data with no * specified format, and is sent unaltered in the call to * {IERC1155Receiver-onERC1155Received} on the receiver of the minted token. */ function _getAddress(bytes memory data) public pure returns (address addr) { // solhint-disable-next-line no-inline-assembly assembly { addr := mload(add(data, 20)) } } /** * @dev Save contract size by wrappng external call into an internal */ function _getAddressRegistryAddress(IAddressRegistry reg, bytes32 data) private view returns (address) { return reg.getRegistryEntry(data); } /** * @dev Save contract size by wrappng external call into an internal */ function _addressToTokenId(address tokenAddress) private view returns (uint256) { return _sftHolder.addressToTokenId(tokenAddress); } /** * @dev internal mint + event emiting */ function _mintAndEmit(address recipient, uint256 tokenId) private { _mint(recipient, tokenId, 1, ''); // Rarible needs to be informed about fees emit SecondarySaleFees(tokenId, getFeeRecipients(0), getFeeBps(0)); } /** * @dev Calculate a 128-bit hash for making tokenIds unique to underlying asset * * @param sftTokenId The tokenId from SFT contract from that we use the first 128 bit * TokenIds in SFT contract are limited to max 128 Bit in WowsSftMinter contract. */ function _hashedTokenId(uint256 sftTokenId) private view returns (uint256) { bytes memory hashData; uint256[] memory tokenIds; uint256 tokenIdsLength; if (sftTokenId.isBaseCard()) { // It's a base card, calculate hash using all cfolioItems address cfolio = _sftHolder.tokenIdToAddress(sftTokenId); require(cfolio != address(0), 'TF: src token invalid'); tokenIds = _sftHolder.getTokenIds(cfolio); tokenIdsLength = tokenIds.length; hashData = abi.encodePacked(address(this), sftTokenId); } else { // It's a cfolioItem itself, only calculate underlying value tokenIds = new uint256[](1); tokenIds[0] = sftTokenId; tokenIdsLength = 1; } // Run through all cfolioItems and let their single CFolioItemHandler // append hashable data for (uint256 i = 0; i < tokenIdsLength; ++i) { address cfolio = _sftHolder.tokenIdToAddress(tokenIds[i].toSftTokenId()); require(cfolio != address(0), 'TF: item token invalid'); address handler = IWOWSCryptofolio(cfolio).handler(); require(handler != address(0), 'TF: item handler invalid'); hashData = ICFolioItemCallback(handler).appendHash(cfolio, hashData); } uint256 hashNum = uint256(keccak256(hashData)); return (hashNum ^ (hashNum << 128)).maskHash() | sftTokenId; } } /* * Copyright (C) 2020-2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 AND MIT * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; import '../../0xerc1155/access/AccessControl.sol'; import '../../0xerc1155/tokens/ERC1155/ERC1155Metadata.sol'; import '../../0xerc1155/tokens/ERC1155/ERC1155MintBurn.sol'; /** * @dev Partial implementation of https://eips.ethereum.org/EIPS/eip-1155[ERC1155] * Multi Token Standard */ contract WOWSMinterPauser is Context, AccessControl, ERC1155MintBurn, ERC1155Metadata { ////////////////////////////////////////////////////////////////////////////// // Roles ////////////////////////////////////////////////////////////////////////////// // Role to mint new tokens bytes32 public constant MINTER_ROLE = 'MINTER_ROLE'; ////////////////////////////////////////////////////////////////////////////// // State ////////////////////////////////////////////////////////////////////////////// // Pause bool private _pauseActive; ////////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////////// // Event triggered when _pause state changed event Pause(bool active); ////////////////////////////////////////////////////////////////////////////// // Constructor ////////////////////////////////////////////////////////////////////////////// constructor() {} ////////////////////////////////////////////////////////////////////////////// // Pausing interface ////////////////////////////////////////////////////////////////////////////// /** * @dev Pauses all token transfers. * * Requirements: * * - The caller must have the `DEFAULT_ADMIN_ROLE`. */ function pause(bool active) public { // Validate access require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Only admin'); if (_pauseActive != active) { // Update state _pauseActive = active; emit Pause(active); } } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _pauseActive; } function _pause(bool active) internal { _pauseActive = active; } ////////////////////////////////////////////////////////////////////////////// // Minting interface ////////////////////////////////////////////////////////////////////////////// /** * @dev Creates `amount` new tokens for `to`, of token type `tokenId`. * * See {ERC1155-_mint}. * * Requirements: * * - The caller must have the `MINTER_ROLE`. */ function mint( address to, uint256 tokenId, uint256 amount, bytes memory data ) public virtual { // Validate access require(hasRole(MINTER_ROLE, _msgSender()), 'Only minter'); // Validate parameters require(to != address(0), "Can't mint to zero address"); // Update state _mint(to, tokenId, amount, data); } /** * @dev Batched variant of {mint}. */ function mintBatch( address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) public virtual { // Validate access require(hasRole(MINTER_ROLE, _msgSender()), 'Only minter'); // Validate parameters require(to != address(0), "Can't mint to zero address"); require(tokenIds.length == amounts.length, "Lengths don't match"); // Update state _batchMint(to, tokenIds, amounts, data); } ////////////////////////////////////////////////////////////////////////////// // Burning interface ////////////////////////////////////////////////////////////////////////////// function burn( address account, uint256 id, uint256 value ) public virtual { // Validate access require( account == _msgSender() || isApprovedForAll(account, _msgSender()), 'Caller is not owner nor approved' ); // Update state _burn(account, id, value); } function burnBatch( address account, uint256[] calldata ids, uint256[] calldata values ) public virtual { // Validate access require( account == _msgSender() || isApprovedForAll(account, _msgSender()), 'Caller is not owner nor approved' ); // Update state _batchBurn(account, ids, values); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ERC1155} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ERC1155-_beforeTokenTransfer}. * * This function is necessary due to diamond inheritance. */ function _beforeTokenTransfer( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) internal virtual override { // Validate state require(!_pauseActive, 'Transfer operation paused!'); // Call ancestor super._beforeTokenTransfer(operator, from, to, tokenId, amount, data); } /** * @dev See {ERC1155-_beforeBatchTokenTransfer}. * * This function is necessary due to diamond inheritance. */ function _beforeBatchTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual override { // Valiate state require(!_pauseActive, 'Transfer operation paused!'); // Call ancestor super._beforeBatchTokenTransfer( operator, from, to, tokenIds, amounts, data ); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ERC165} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ERC165-supportsInterface} */ function supportsInterface(bytes4 _interfaceID) public pure virtual override(ERC1155, ERC1155Metadata) returns (bool) { return super.supportsInterface(_interfaceID); } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @dev Interface to receive callbacks when minted tokens are burnt */ interface ICFolioItemCallback { /** * @dev Called when a TradeFloor CFolioItem is transfered * * In case of mint `from` is address(0). * In case of burn `to` is address(0). * * cfolioHandlers are passed to let each cfolioHandler filter for its own * token. This eliminates the need for creating separate lists. * * @param from The account sending the token * @param to The account receiving the token * @param tokenIds The ERC-1155 token IDs * @param cfolioHandlers cFolioItem handlers */ function onCFolioItemsTransferedFrom( address from, address to, uint256[] calldata tokenIds, address[] calldata cfolioHandlers ) external; /** * @dev Append data we use later for hashing * * @param cfolioItem The token ID of the c-folio item * @param current The current data being hashes * * @return The current data, with internal data appended */ function appendHash(address cfolioItem, bytes calldata current) external view returns (bytes memory); } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @notice Cryptofolio interface */ interface IWOWSCryptofolio { ////////////////////////////////////////////////////////////////////////////// // Getter ////////////////////////////////////////////////////////////////////////////// /** * @dev Return the handler (CFIH) of the underlying NFT */ function handler() external view returns (address); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @dev Set the handler of the underlying NFT * * This function is called during I-NFT setup * * @param newHandler The new handler of the underlying NFT, */ function setHandler(address newHandler) external; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @notice Sft holder contract */ interface IWOWSERC1155 { ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Get the token ID of a given address * * A cross check is required because token ID 0 is valid. * * @param tokenAddress The address to convert to a token ID * * @return The token ID on success, or uint256(-1) if `tokenAddress` does not * belong to a token ID */ function addressToTokenId(address tokenAddress) external view returns (uint256); /** * @dev Get the address for a given token ID * * @param tokenId The token ID to convert * * @return The address, or address(0) in case the token ID does not belong * to an NFT */ function tokenIdToAddress(uint256 tokenId) external view returns (address); /** * @dev Return the level and the mint timestamp of tokenId * * @param tokenId The tokenId to query * * @return mintTimestamp The timestamp token was minted * @return level The level token belongs to */ function getTokenData(uint256 tokenId) external view returns (uint64 mintTimestamp, uint8 level); /** * @dev Return all tokenIds owned by account */ function getTokenIds(address account) external view returns (uint256[] memory); /** * @dev Returns the cFolioItemType of a given cFolioItem tokenId */ function getCFolioItemType(uint256 tokenId) external view returns (uint256); /** * @notice Get the balance of an account's Tokens * @param owner The address of the token holder * @param tokenId ID of the Token * @return The _owner's balance of the token type requested */ function balanceOf(address owner, uint256 tokenId) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param owners The addresses of the token holders * @param tokenIds ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch( address[] calldata owners, uint256[] calldata tokenIds ) external view returns (uint256[] memory); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @notice Mints tokenIds into 'to' account * @dev Emits SftTokenTransfer Event * * Throws if sender has no MINTER_ROLE * 'data' holds the CFolioItemHandler if CFI's are minted */ function mintBatch( address to, uint256[] calldata tokenIds, bytes calldata data ) external; /** * @notice Burns tokenIds owned by 'account' * @dev Emits SftTokenTransfer Event * * Burns all owned CFolioItems * Throws if CFolioItems have assets */ function burnBatch(address account, uint256[] calldata tokenIds) external; /** * @notice Transfers amount of an id from the from address to the 'to' address specified * @dev Emits SftTokenTransfer Event * Throws if 'to' is the zero address * Throws if 'from' is not the current owner * If 'to' is a smart contract, ERC1155TokenReceiver interface will checked * @param from Source address * @param to Target address * @param tokenId ID of the token type * @param amount Transfered amount * @param data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address from, address to, uint256 tokenId, uint256 amount, bytes calldata data ) external; /** * @dev Batch version of {safeTransferFrom} */ function safeBatchTransferFrom( address from, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) external; /** * @dev Each custom card has its own level. Level will be used when * calculating rewards and raiding power. * * @param tokenId The ID of the token whose level is being set * @param cardLevel The new level of the specified token */ function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external; /** * @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used * sftHolder tokenId expected (without hash) */ function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external; /** * @dev Sets external NFT for display tokenId * By default NFT is rendered using our internal metadata * * Throws if not called from MINTER role */ function setExternalNft( uint256 tokenId, address externalCollection, uint256 externalTokenId ) external; /** * @dev Deletes external NFT settings * * Throws if not called from MINTER role */ function deleteExternalNft(uint256 tokenId) external; } /* * Copyright (C) 2020-2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; library AddressBook { bytes32 public constant DEPLOYER = 'DEPLOYER'; bytes32 public constant TEAM_WALLET = 'TEAM_WALLET'; bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET'; bytes32 public constant ADMIN_ACCOUNT = 'ADMIN_ACCOUNT'; bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02'; bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM'; bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN'; bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR'; bytes32 public constant WOWS_BOOSTER_PROXY = 'WOWS_BOOSTER_PROXY'; bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER'; bytes32 public constant SFT_MINTER_PROXY = 'SFT_MINTER_PROXY'; bytes32 public constant SFT_HOLDER_PROXY = 'SFT_HOLDER_PROXY'; bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY'; bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY'; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; library TokenIds { // 128 bit underlying hash uint256 public constant HASH_MASK = (1 << 128) - 1; function isBaseCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) < (1 << 64); } function isStockCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) < (1 << 32); } function isCustomCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) >= (1 << 32) && (tokenId & HASH_MASK) < (1 << 64); } function isCFolioCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128); } function toSftTokenId(uint256 tokenId) internal pure returns (uint256) { return tokenId & HASH_MASK; } function maskHash(uint256 tokenId) internal pure returns (uint256) { return tokenId & ~HASH_MASK; } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; interface IAddressRegistry { /** * @dev Set an abitrary key / address pair into the registry */ function setRegistryEntry(bytes32 _key, address _location) external; /** * @dev Get a registry enty with by key, returns 0 address if not existing */ function getRegistryEntry(bytes32 _key) external view returns (address); }
| Query if a contract implements an interface _interfaceID The interface identifier, as specified in ERC-165 return `true` if the contract implements `_interfaceID` and/
function _beforeTokenTransfer( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data function _beforeBatchTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data | ERC165 Functions | |__________________________________*/ function supportsInterface(bytes4 _interfaceID) public pure virtual override returns (bool) { if (_interfaceID == type(IERC1155).interfaceId) { return true; } return super.supportsInterface(_interfaceID); }
389,834
./full_match/5/0xa951c77EA547661e55875a1B7010945fB6d0c61b/sources/contracts/pomoERC20.sol
Check that the sender has enough ETH to cover the gas fees and protocol fee
function claim(address _to) public payable { require( msg.value >= protocolFee, "Not enough Ether to cover transaction" ); transfer(_to, tokenEmission); emit TokenClaim(_to); }
11,618,089
./partial_match/1/0x28Ad7B6FAaCDf1D5Ff31953E838c1AE6B4aA24fc/sources/taxercoin.sol
uint256 tokensToLiquify = _balances[address(this)];
function swapBack() internal lockTheSwap { uint256 tokensToLiquify = swapThreshold; uint256 amountToLiquify = tokensToLiquify .mul(liquidityFee) .div(totalFee) .div(2); uint256 amountToSwap = tokensToLiquify.sub(amountToLiquify); address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountETH = address(this).balance; uint256 totalETHFee = totalFee.sub(liquidityFee.div(2)); uint256 amountETHMarketing = amountETH.mul(marketingFee).div( totalETHFee ); uint256 amountETHTaxer = amountETH.mul(TaxerFee).div(totalETHFee); uint256 amountETHLiquidity = amountETH .mul(liquidityFee) .div(totalETHFee) .div(2); (bool tmpSuccess, ) = payable(marketingWallet).call{ value: amountETHMarketing, gas: 30000 }(""); (bool tmpSuccess2, ) = payable(Taxer).call{ value: amountETHTaxer, gas: 30000 }(""); emit TaxerPayout(Taxer, amountETHTaxer); tmpSuccess2 = false; if (amountToLiquify > 0) { address(this), amountToLiquify, 0, 0, autoLiquidityReceiver, block.timestamp ); emit AutoLiquify(amountETHLiquidity, amountToLiquify); } }
9,258,161
./partial_match/1/0x209C860Cf96cd3968b6D0AaAB1d5e13C62632bf5/sources/Remember43.sol
Modify victim infomation. Only owner and contributor can use this function to modify victim infomation. It can be modified only within the time limit. _idx Index of victim. _name Name of victim. _addr Local address of victim./
function modifyVictim(uint16 _idx, string memory _name, string memory _addr) onlyContributor public { require(victims[_idx].createTime + timeout > now); victims[_idx].name = _name; victims[_idx].addr = _addr; emit victimModified(victims[_idx].idx, victims[_idx].name, victims[_idx].addr, victims[_idx].createTime); }
16,049,252
// File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract 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/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (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 /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol /** * @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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: contracts/ISTAKING.sol /** * @dev Interface of the ISTAKING */ interface ISTAKING { /** * @dev Returns the name of reward tokens. */ function asset() external view returns (string memory); /** * @dev Returns the address of reward tokens. */ function assetAddr() external view returns (address[] memory); /** * @dev Returns the total amount of staking. */ function totalBalance() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Stake for mining. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Staking} event. */ function staking(address beneficiary, uint256 amount) external returns (bool); /** * @dev This function withdraws the staked MPLE and reward tokens for mining. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Withdraw} event. */ function withdraw(address beneficiary, uint256 amount) external returns (bool); /** * @dev Returns whether reward has been confirmed. * */ function isconfirm() external returns (bool); /** * @dev Return the rewards you can receive. Returns 0 if the reward has not been confirmed. */ function reward(address account) external view returns (uint256); /** * @dev Returns the past time since deposit. */ function term(address account) external view returns (uint256); /** * @dev Returns the staking open date */ function beginAt() external view returns (uint256); /** * @dev Returns the staking close date. */ function endAt() external view returns (uint256); /** * @dev Returns the staking regist time. */ function registAt(address account) external view returns (uint256); /** * @dev Returns the staking exit time. */ function exitAt(address account) external view returns (uint256); /** * @dev Emitted when the token stakes. */ event Staking(address indexed from, uint256 value); /** * @dev Emitted when the owner makes a withdrawal. */ event Withdraw(address indexed owner, uint256 value); } // File: contracts/MPLE.sol contract MPLE is ERC20, ERC20Burnable { /** security for math*/ using SafeMath for uint256; /** security for address*/ using Address for address; /** inital supply*/ uint256 public INITAL_SUPPLY = 1000000000*(10**18); /** staking contract */ ISTAKING public stakingContract; bool private _paused; address private _owner; /** staking activation config */ bool public stakingFinished = true; bool public stakingLocked = true; /** List of agents allowed to manage staking */ mapping (address => bool) public stakingManagers; /** * @dev Check if staking is possible. */ modifier canStaking() { require(!stakingFinished, "[Validation] The staking did not open."); _; } /** * @dev Check if staking is possible. */ modifier canWithdraw() { require(!stakingLocked, "[Validation] The staking did not open."); _; } /** * @dev Check if you are a staking manager. */ modifier onlyManagers() { require(stakingManagers[msg.sender], "[Validation] sender is not a staking manager."); _; } /** * @dev Check if it is a smart contract. */ modifier onlyContract(address account) { require(account.isContract(), "[Validation] The address does not contain a contract"); _; } /** * @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"); _; } constructor() ERC20("MPLE", "MPLE") { _mint((msg.sender), INITAL_SUPPLY); _paused = false; _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev _beforeTokenTransfer overide */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20) { ERC20._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } /** * @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 Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public whenNotPaused onlyOwner { _paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public whenPaused onlyOwner { _paused = false; emit Unpaused(msg.sender); } /** * @dev setup staking manager */ function setManager(address addr, bool state) public onlyOwner { stakingManagers[addr] = state; emit ManagerChanged(addr, state); } /** * @dev set staking Contract */ function setStakingContract(address contractAddr) public onlyOwner onlyContract(contractAddr) { stakingContract = ISTAKING(contractAddr); emit StakingContractChanged(contractAddr); } /** * @dev Make staking possible. */ function openStaking() public onlyManagers { stakingFinished = false; emit StakingOpened(); } /** * @dev stop staking */ function closeStaking() public onlyManagers { stakingFinished = true; emit StakingFinished(); } /** * @dev Staking for mining. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Staking} event. */ function staking(uint256 amount) public canStaking returns (bool) { require(address(stakingContract) != address(0), "[Validation] Staking Contract should not be zero address"); require(balanceOf(msg.sender) >= amount, "[Validation] The balance is insufficient."); _transfer(msg.sender, address(stakingContract), amount); return stakingContract.staking(msg.sender, amount); } /** * @dev This function withdraws the staked MPLE and reward tokens for mining. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Withdraw} event. */ function withdraw(uint256 amount) public canWithdraw returns (bool) { return stakingContract.withdraw(msg.sender, amount); } /** * @dev This is a function for withdrawal of erc20 tokens. * * Emits a {Withdraw} event. */ function withdrawErc20(address _tokenAddr, address _to, uint _value) public onlyOwner { ERC20 erc20 = ERC20(_tokenAddr); erc20.transfer(_to, _value); emit WithdrawErc20Token(_tokenAddr, _to, _value); } /** * @dev This is a function for mint. * * Emits a {Withdraw} event. */ function mint(address account, uint256 amount) public onlyOwner { require(INITAL_SUPPLY >= totalSupply().add(amount), "[Validation] Total supply cannot exceed the initial supply."); _mint(account, amount); } /** events */ event StakingOpened(); event StakingFinished(); event StakingContractChanged(address indexed stakingContract); event ManagerChanged(address indexed manager, bool state); event WithdrawErc20Token (address indexed erc20, address indexed wallet, uint value); event Paused(address account); event Unpaused(address account); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); }
This is a function for mint. Emits a {Withdraw} event./
function mint(address account, uint256 amount) public onlyOwner { require(INITAL_SUPPLY >= totalSupply().add(amount), "[Validation] Total supply cannot exceed the initial supply."); _mint(account, amount); } event StakingFinished(); event StakingContractChanged(address indexed stakingContract); event ManagerChanged(address indexed manager, bool state); event WithdrawErc20Token (address indexed erc20, address indexed wallet, uint value); event Paused(address account); event Unpaused(address account); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
5,950,862
// SPDX-License-IdentifierL: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract NFTMarket is ReentrancyGuard { /** * General Init. (item is reffering to NFT) * * @param _itemsIds counter of the item ID's, inherit from Counters * @param _itemsSold counter of the amount of items sold, inherit from Counters * @param owner address representing the owner of the item * @param listingPrice integer representing the listing price of the item * @param idToMarketItem struct of key and value pairs holding all the items (ex. idToMarketItem[1111]) */ using Counters for Counters.Counter; Counters.Counter private _itemIds; Counters.Counter private _itemsSold; address payable owner; uint256 listingPrice = 0.025 ether; constructor() { owner = payable(msg.sender); } struct MarketItem { uint256 itemId; address nftContract; uint256 tokenId; address payable seller; address payable owner; uint256 price; bool sold; } mapping(uint256 => MarketItem) private idToMarketItem; event MarketItemCreated( uint256 indexed itemId, address indexed nftContract, uint256 indexed tokenId, address seller, address owner, uint256 price, bool sold ); function getListingPrice() public view returns (uint256) { return listingPrice; } function createMarketItem( address nftContract, uint256 tokenId, uint256 price ) public payable nonReentrant { require(price > 0, "Price must be at least 1 wei."); require( msg.value == listingPrice, "Price must be equal to listing price." ); _itemIds.increment(); uint256 itemId = _itemIds.current(); // Current MarketItem struct ready to ship. idToMarketItem[itemId] = MarketItem( itemId, nftContract, tokenId, payable(msg.sender), payable(address(0)), price, false ); // Transfer Ownership IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId); // Trigger the item creation event emit MarketItemCreated( itemId, nftContract, tokenId, msg.sender, address(0), price, false ); } function createMarketSale(address nftContract, uint256 itemId) public payable nonReentrant { uint256 price = idToMarketItem[itemId].price; uint256 tokenId = idToMarketItem[itemId].tokenId; // Check if the buyer is asking for the actual price of the item. require( msg.value == price, "Pleasse Submit the asking price in order to complete the purchase." ); // Transfer the value of the transaction to the seller. idToMarketItem[itemId].seller.transfer(msg.value); // Tranfer the ownership of the token to the buyer. IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId); // Setting the buyer address to be the owner of the token. idToMarketItem[itemId].owner = payable(msg.sender); // Setting the item to sold. idToMarketItem[itemId].sold = true; // Incrementing the amount of items sold. _itemsSold.increment(); // Pay the owner of the contract. ( Commission for the market place creator :) ) payable(owner).transfer(listingPrice); } // Fetching all market items. function fetchMarketItems() public view returns (MarketItem[] memory) { uint256 itemCount = _itemIds.current(); uint256 unsoldItemCount = _itemIds.current() - _itemsSold.current(); uint256 currentIndex = 0; MarketItem[] memory items = new MarketItem[](unsoldItemCount); for (uint256 i = 0; i < itemCount; i++) { if (idToMarketItem[i + 1].owner == address(0)) { uint256 currentId = idToMarketItem[i + 1].itemId; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } // Fetching the NFT's list the user posses. function fetchMyNFTs() public view returns (MarketItem[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { uint256 currentId = idToMarketItem[i + 1].itemId; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } // Fetching the NFT's the user created himself. function fetchItemsCreated() public view returns (MarketItem[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint256 currentId = idToMarketItem[i + 1].itemId; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } }
Fetching the NFT's the user created himself.
function fetchItemsCreated() public view returns (MarketItem[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint256 currentId = idToMarketItem[i + 1].itemId; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
13,011,380
pragma solidity ^0.8.1; import "@openzeppelin/contracts/access/Ownable.sol"; import "prb-math/contracts/PRBMathUD60x18.sol"; import "hardhat/console.sol"; contract Voting is Ownable { using PRBMathUD60x18 for uint256; // TODO: Emit these events event VoteCast(uint voteRoundId, address voter, uint orgId, uint weight); event VotingStarted(uint voteRoundId); event VotingEnded(uint voteRoundId); event VoteExecuted(uint voteRoundId, address recipient, uint totalAmount); event AddOrganization(uint indexed pid, address orgWallet, string name, string description, address proposer); struct Vote { uint recipientOrg; uint weight; bool isExist; // Flag to differentiate between an actual vote and default empty struct in mapping } // staging -> gathering interest/registering organizations enum VotingStage { STAGING, IN_PROGRESS, ENDED, PAID_OUT } struct OrgInfo { uint orgId; address payable orgWallet; string orgName; string description; address proposer; } struct VotingRoundDetails { uint votingStart; uint votingEnd; uint totalVotesCast; bool executed; string description; VotingStage stage; uint[] orgs; mapping(uint => bool) participatingOrgs; mapping(uint => uint) votesReceived; mapping(address => Vote) userVotes; } OrgInfo[] public orgsInfo; // Public so that info can be queried. mapping(address => bool) public orgExistence; // Public so that info can be queried. uint voteRoundCounter = 0; uint stagingPeriod = 3 days; uint votingPeriod = 1 weeks; uint currentVoteRoundId = 0; mapping(uint => VotingRoundDetails) votingRounds; function getVotingRoundDetails() view external returns( uint, uint, uint, bool, string memory, string memory, uint[] memory, uint[] memory, uint ) { VotingRoundDetails storage currRound = votingRounds[currentVoteRoundId]; string memory currStage; if (currRound.stage == VotingStage.STAGING) { currStage = 'Staging'; } else if (currRound.stage == VotingStage.IN_PROGRESS) { currStage = 'In Progress'; } else if (currRound.stage == VotingStage.ENDED) { currStage = 'Ended'; } else if (currRound.stage == VotingStage.PAID_OUT) { currStage = 'Paid Out'; } return ( currRound.votingStart, currRound.votingEnd, currRound.totalVotesCast, currRound.executed, currRound.description, currStage, currRound.orgs, compileVotesReceived(currRound), currentVoteRoundId ); } // helper fn to convert VotingRoundDetails.votesRecevied into an indexable array to return function compileVotesReceived(VotingRoundDetails storage _round) internal view returns (uint[] memory) { uint[] memory votesReceived = new uint[](_round.orgs.length); for (uint i = 0; i < _round.orgs.length; i++) { uint orgId = _round.orgs[i]; votesReceived[i] = _round.votesReceived[orgId]; } return votesReceived; } // Start a new round of voting, description can be used to describe the // category of organizations taking part, e.g "Animals" or "Elderly" (?) // For now only owner can start a new round function newRound(string memory _description, uint[] memory _orgIds) external onlyOwner() { voteRoundCounter++; uint newRoundId = voteRoundCounter; currentVoteRoundId = newRoundId; uint voteStartTime = block.timestamp + stagingPeriod; votingRounds[newRoundId].votingStart = voteStartTime; votingRounds[newRoundId].votingEnd = voteStartTime + votingPeriod; votingRounds[newRoundId].description = _description; votingRounds[newRoundId].stage = VotingStage.IN_PROGRESS; votingRounds[newRoundId].orgs = _orgIds; for (uint i = 0; i < _orgIds.length; i++) { uint orgId = _orgIds[i]; votingRounds[newRoundId].participatingOrgs[orgId] = true; votingRounds[newRoundId].votesReceived[orgId] = 0; } } // DEPRECATED? Owner should specify a list of orgs when creating the round since we're skipping staging. function registerOrg(uint _voteRoundId, uint _orgId) external onlyOwner() { require(votingRounds[_voteRoundId].stage == VotingStage.STAGING, "Orgs can only be registered during the staging period"); votingRounds[_voteRoundId].orgs.push(_orgId); votingRounds[_voteRoundId].participatingOrgs[_orgId] = true; } // TODO: How to accept donation? // Make the vote function itself payable? make user exchange for token? function vote(uint _voteRoundId, uint _orgId) payable external { VotingRoundDetails storage currRound = votingRounds[_voteRoundId]; if (block.timestamp > currRound.votingEnd) { votingRounds[_voteRoundId].stage = VotingStage.ENDED; } require(currRound.stage == VotingStage.IN_PROGRESS, "Votes can only be cast if voting is still in progress"); require(_canVote(_voteRoundId, msg.sender), "User not allowed to vote in this round"); require(_isValidOrg(_voteRoundId, _orgId), "Not a valid organization id"); /* fkin give up on quadratic voting cos idk how to use the library's sqrt */ // uint voteWeight = (2 * (msg.value / conversionFactor)).sqrt(); // quadratic voting uint conversionFactor = 10 ** 15; // convert wei to units of 0.001 ether (not 1 ether) // That means 1 vote costs 0.001 ETH, which is somewhat reasonable uint voteWeight = msg.value / conversionFactor; currRound.userVotes[msg.sender] = Vote(_orgId, voteWeight, true); currRound.votesReceived[_orgId] += voteWeight; currRound.totalVotesCast += voteWeight; } function executeVotingRound(uint _voteRoundId) external returns(bool) { VotingRoundDetails storage voteRound = votingRounds[_voteRoundId]; require(block.timestamp > voteRound.votingEnd, "Can only execute contract after voting has ended"); uint winningOrg = _getMostVotedOrg(_voteRoundId); address payable winningOrgAddr = orgsInfo[winningOrg].orgWallet; winningOrgAddr.transfer(address(this).balance); voteRound.stage = VotingStage.PAID_OUT; return true; } function getWinningOrg(uint _voteRoundId) external view returns(bool, OrgInfo memory) { VotingRoundDetails storage voteRound = votingRounds[_voteRoundId]; if (voteRound.stage != VotingStage.PAID_OUT) { return (false, orgsInfo[0]); // just return a random org, too lazy to find a cleaner way } uint winningOrgId = _getMostVotedOrg(_voteRoundId); for (uint i = 0; i < orgsInfo.length; i++) { if (orgsInfo[i].orgId == winningOrgId) { return (true, orgsInfo[i]); } } return (false, orgsInfo[0]); // just return a random org, too lazy to find a cleaner way } function _getMostVotedOrg(uint _voteRoundId) private view returns(uint) { VotingRoundDetails storage votingDetails = votingRounds[_voteRoundId]; uint winningOrgId; uint maxScore; for (uint i = 0; i < votingDetails.orgs.length; i++) { uint currOrg = votingDetails.orgs[i]; if (votingDetails.votesReceived[currOrg] > maxScore) { winningOrgId = currOrg; maxScore = votingDetails.votesReceived[currOrg]; } } return winningOrgId; } function _canVote(uint _voteRoundId, address _user) private pure returns(bool) { // TODO: Implement voting permission check return _voteRoundId == _voteRoundId && _user == _user; } function _hasNotVoted(uint _voteRoundId, address _user) private view returns(bool) { return !votingRounds[_voteRoundId].userVotes[_user].isExist; } function _isValidOrg(uint _voteRoundId, uint _orgId) private view returns(bool) { return votingRounds[_voteRoundId].participatingOrgs[_orgId]; } modifier nonDuplicated(address _orgWallet) { require(orgExistence[_orgWallet] == false, "Org wallet is duplicated"); _; } function addOrganization(address payable _orgWallet, string memory _orgName, string memory _description) external nonDuplicated(_orgWallet) { orgsInfo.push( OrgInfo({ orgId: orgsInfo.length, orgWallet: _orgWallet, orgName: _orgName, description: _description, proposer: msg.sender })); orgExistence[_orgWallet] = true; emit AddOrganization(orgsInfo.length, _orgWallet, _orgName, _description, msg.sender); } function getOrgsInfo() external view returns (OrgInfo[] memory) { return orgsInfo; } }
DEPRECATED? Owner should specify a list of orgs when creating the round since we're skipping staging.
function registerOrg(uint _voteRoundId, uint _orgId) external onlyOwner() { require(votingRounds[_voteRoundId].stage == VotingStage.STAGING, "Orgs can only be registered during the staging period"); votingRounds[_voteRoundId].orgs.push(_orgId); votingRounds[_voteRoundId].participatingOrgs[_orgId] = true; }
12,603,810
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./libraries/DecimalsConverter.sol"; import "./interfaces/ICapitalPool.sol"; import "./interfaces/IClaimingRegistry.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/ILeveragePortfolio.sol"; import "./interfaces/ILiquidityRegistry.sol"; import "./interfaces/IPolicyBook.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/IYieldGenerator.sol"; import "./interfaces/ILeveragePortfolioView.sol"; import "./abstract/AbstractDependant.sol"; import "./Globals.sol"; contract CapitalPool is ICapitalPool, OwnableUpgradeable, AbstractDependant { using SafeERC20 for ERC20; using SafeMath for uint256; using Math for uint256; uint256 public constant ADDITIONAL_WITHDRAW_PERIOD = 1 days; IClaimingRegistry public claimingRegistry; IPolicyBookRegistry public policyBookRegistry; IYieldGenerator public yieldGenerator; ILeveragePortfolio public reinsurancePool; ILiquidityRegistry public liquidityRegistry; ILeveragePortfolioView public leveragePortfolioView; ERC20 public stblToken; // reisnurance pool vStable balance updated by(premium, interest from defi) uint256 public reinsurancePoolBalance; // user leverage pool vStable balance updated by(premium, addliq, withdraw liq) mapping(address => uint256) public leveragePoolBalance; // policy books vStable balances updated by(premium, addliq, withdraw liq) mapping(address => uint256) public regularCoverageBalance; // all hStable capital balance , updated by (all pool transfer + deposit to dfi + liq cushion) uint256 public hardUsdtAccumulatedBalance; // all vStable capital balance , updated by (all pool transfer + withdraw from liq cushion) uint256 public override virtualUsdtAccumulatedBalance; // pool balances tracking uint256 public override liquidityCushionBalance; address public maintainer; uint256 public stblDecimals; // new state post v2 deployemnt bool public isLiqCushionPaused; bool public automaticHardRebalancing; uint256 public override rebalanceDuration; bool private deployFundsToDefi; event PoolBalancesUpdated( uint256 hardUsdtAccumulatedBalance, uint256 virtualUsdtAccumulatedBalance, uint256 liquidityCushionBalance, uint256 reinsurancePoolBalance ); event LiquidityCushionRebalanced( uint256 liquidityNeede, uint256 liquidityWithdraw, uint256 liquidityDeposit ); modifier broadcastBalancing() { _; emit PoolBalancesUpdated( hardUsdtAccumulatedBalance, virtualUsdtAccumulatedBalance, liquidityCushionBalance, reinsurancePoolBalance ); } modifier onlyPolicyBook() { require(policyBookRegistry.isPolicyBook(msg.sender), "CAPL: Not a PolicyBook"); _; } modifier onlyReinsurancePool() { require( address(reinsurancePool) == _msgSender(), "RP: Caller is not a reinsurance pool contract" ); _; } modifier onlyClaimingRegistry() { require( address(claimingRegistry) == _msgSender(), "CP: Caller is not claiming registry contract" ); _; } modifier onlyMaintainer() { require(_msgSender() == maintainer, "CP: not maintainer"); _; } function __CapitalPool_init() external initializer { __Ownable_init(); maintainer = _msgSender(); rebalanceDuration = 3 days; deployFundsToDefi = true; } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { claimingRegistry = IClaimingRegistry(_contractsRegistry.getClaimingRegistryContract()); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); stblToken = ERC20(_contractsRegistry.getUSDTContract()); yieldGenerator = IYieldGenerator(_contractsRegistry.getYieldGeneratorContract()); reinsurancePool = ILeveragePortfolio(_contractsRegistry.getReinsurancePoolContract()); liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract()); leveragePortfolioView = ILeveragePortfolioView( _contractsRegistry.getLeveragePortfolioViewContract() ); stblDecimals = stblToken.decimals(); } /// @notice distributes the policybook premiums into pools (CP, ULP , RP) /// @dev distributes the balances acording to the established percentages /// @param _stblAmount amount hardSTBL ingressed into the system /// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param _protocolFee uint256 the amount of protocol fee earned by premium function addPolicyHoldersHardSTBL( uint256 _stblAmount, uint256 _epochsNumber, uint256 _protocolFee ) external override onlyPolicyBook broadcastBalancing returns (uint256) { PremiumFactors memory factors; factors.vStblOfCP = regularCoverageBalance[_msgSender()]; factors.premiumPrice = _stblAmount.sub(_protocolFee); factors.policyBookFacade = IPolicyBookFacade(IPolicyBook(_msgSender()).policyBookFacade()); factors.vStblDeployedByRP = DecimalsConverter.convertFrom18( factors.policyBookFacade.VUreinsurnacePool(), stblDecimals ); factors.userLeveragePoolsCount = factors.policyBookFacade.countUserLeveragePools(); factors.epochsNumber = _epochsNumber; uint256 reinsurancePoolPremium; uint256 coveragePoolPremium; if (factors.vStblDeployedByRP == 0 && factors.userLeveragePoolsCount == 0) { coveragePoolPremium = factors.premiumPrice; } else { (reinsurancePoolPremium, coveragePoolPremium) = _calcPremiumForAllPools(factors); } uint256 reinsurancePoolTotalPremium = reinsurancePoolPremium.add(_protocolFee); reinsurancePoolBalance = reinsurancePoolBalance.add(reinsurancePoolTotalPremium); reinsurancePool.addPolicyPremium( _epochsNumber, DecimalsConverter.convertTo18(reinsurancePoolTotalPremium, stblDecimals) ); regularCoverageBalance[_msgSender()] = regularCoverageBalance[_msgSender()].add( coveragePoolPremium ); hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(_stblAmount); virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.add(_stblAmount); return DecimalsConverter.convertTo18(coveragePoolPremium, stblDecimals); } function _calcPremiumForAllPools(PremiumFactors memory factors) internal returns (uint256 reinsurancePoolPremium, uint256 coveragePoolPremium) { uint256 _totalCoverTokens = DecimalsConverter.convertFrom18( (IPolicyBook(_msgSender())).totalCoverTokens(), stblDecimals ); factors.poolUtilizationRation = _totalCoverTokens.mul(PERCENTAGE_100).div( factors.vStblOfCP ); uint256 _participatedLeverageAmounts; if (factors.userLeveragePoolsCount > 0) { address[] memory _userLeverageArr = factors.policyBookFacade.listUserLeveragePools(0, factors.userLeveragePoolsCount); for (uint256 i = 0; i < _userLeverageArr.length; i++) { _participatedLeverageAmounts = _participatedLeverageAmounts.add( clacParticipatedLeverageAmount(factors, _userLeverageArr[i]) ); } } uint256 totalLiqforPremium = factors.vStblOfCP.add(factors.vStblDeployedByRP).add(_participatedLeverageAmounts); factors.premiumPerDeployment = (factors.premiumPrice.mul(PRECISION)).div( totalLiqforPremium ); reinsurancePoolPremium = _calcReinsurancePoolPremium(factors); if (factors.userLeveragePoolsCount > 0) { _calcUserLeveragePoolPremium(factors); } coveragePoolPremium = _calcCoveragePoolPremium(factors); } /// @notice distributes the hardSTBL from the coverage providers /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addCoverageProvidersHardSTBL(uint256 _stblAmount) external override onlyPolicyBook broadcastBalancing { regularCoverageBalance[_msgSender()] = regularCoverageBalance[_msgSender()].add( _stblAmount ); hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(_stblAmount); virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.add(_stblAmount); } //// @notice distributes the hardSTBL from the leverage providers /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addLeverageProvidersHardSTBL(uint256 _stblAmount) external override onlyPolicyBook broadcastBalancing { leveragePoolBalance[_msgSender()] = leveragePoolBalance[_msgSender()].add(_stblAmount); hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(_stblAmount); virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.add(_stblAmount); } /// @notice distributes the hardSTBL from the reinsurance pool /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addReinsurancePoolHardSTBL(uint256 _stblAmount) external override onlyReinsurancePool broadcastBalancing { reinsurancePoolBalance = reinsurancePoolBalance.add(_stblAmount); hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(_stblAmount); virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.add(_stblAmount); } /// @notice rebalances pools acording to v2 specification and dao enforced policies /// @dev emits PoolBalancesUpdated function rebalanceLiquidityCushion() public override broadcastBalancing onlyMaintainer { require(!isLiqCushionPaused, "CP: liqudity cushion is pasued"); //check defi protocol balances (, uint256 _lostAmount) = yieldGenerator.reevaluateDefiProtocolBalances(); if (_lostAmount > 0) { isLiqCushionPaused = true; if (automaticHardRebalancing) { defiHardRebalancing(); } } // hard rebalancing - Stop all withdrawals from all pools if (isLiqCushionPaused) { hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(liquidityCushionBalance); liquidityCushionBalance = 0; return; } uint256 _pendingClaimAmount = claimingRegistry.getAllPendingClaimsAmount(); uint256 _pendingRewardAmount = claimingRegistry.getAllPendingRewardsAmount(); uint256 _pendingWithdrawlAmount = liquidityRegistry.getAllPendingWithdrawalRequestsAmount(); uint256 _requiredLiquidity = _pendingWithdrawlAmount.add(_pendingClaimAmount).add(_pendingRewardAmount); _requiredLiquidity = DecimalsConverter.convertFrom18(_requiredLiquidity, stblDecimals); (uint256 _deposit, uint256 _withdraw) = getDepositAndWithdraw(_requiredLiquidity); liquidityCushionBalance = _requiredLiquidity; hardUsdtAccumulatedBalance = 0; uint256 _actualAmount; if (_deposit > 0) { stblToken.safeApprove(address(yieldGenerator), 0); stblToken.safeApprove(address(yieldGenerator), _deposit); _actualAmount = yieldGenerator.deposit(_deposit); if (_actualAmount < _deposit) { hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add( (_deposit.sub(_actualAmount)) ); } } else if (_withdraw > 0) { _actualAmount = yieldGenerator.withdraw(_withdraw); if (_actualAmount < _withdraw) { liquidityCushionBalance = liquidityCushionBalance.sub( (_withdraw.sub(_actualAmount)) ); } } emit LiquidityCushionRebalanced(_requiredLiquidity, _withdraw, _deposit); } /// @param _rebalanceDuration parameter passes in seconds function setRebalanceDuration(uint256 _rebalanceDuration) public onlyOwner { require(_rebalanceDuration <= 7 days, "CP: invalid rebalance duration"); rebalanceDuration = _rebalanceDuration; } function defiHardRebalancing() public onlyOwner { (uint256 _totalDeposit, uint256 _lostAmount) = yieldGenerator.reevaluateDefiProtocolBalances(); if (_lostAmount > 0 && _totalDeposit > _lostAmount) { uint256 _lostPercentage = _lostAmount.mul(PERCENTAGE_100).div(virtualUsdtAccumulatedBalance); address[] memory _policyBooksArr = policyBookRegistry.list(0, policyBookRegistry.count()); ///@dev we should update all coverage pools liquidity before leverage pool /// in order to do leverage rebalancing for all pools at once for (uint256 i = 0; i < _policyBooksArr.length; i++) { if (policyBookRegistry.isUserLeveragePool(_policyBooksArr[i])) continue; _updatePoolLiquidity(_policyBooksArr[i], 0, _lostPercentage, PoolType.COVERAGE); } address[] memory _userLeverageArr = policyBookRegistry.listByType( IPolicyBookFabric.ContractType.VARIOUS, 0, policyBookRegistry.countByType(IPolicyBookFabric.ContractType.VARIOUS) ); for (uint256 i = 0; i < _userLeverageArr.length; i++) { _updatePoolLiquidity(_userLeverageArr[i], 0, _lostPercentage, PoolType.LEVERAGE); } yieldGenerator.defiHardRebalancing(); } } /// @dev when calling this function we have to have either _lostAmount == 0 or _lostPercentage == 0 function _updatePoolLiquidity( address _poolAddress, uint256 _lostAmount, uint256 _lostPercentage, PoolType poolType ) internal { IPolicyBook _pool = IPolicyBook(_poolAddress); if (_lostPercentage > 0) { uint256 _currentLiquidity = _pool.totalLiquidity(); _lostAmount = _currentLiquidity.mul(_lostPercentage).div(PERCENTAGE_100); } _pool.updateLiquidity(_lostAmount); uint256 _stblLostAmount = DecimalsConverter.convertFrom18(_lostAmount, stblDecimals); if (poolType == PoolType.COVERAGE) { regularCoverageBalance[_poolAddress] = regularCoverageBalance[_poolAddress].sub( _stblLostAmount ); } else if (poolType == PoolType.LEVERAGE) { leveragePoolBalance[_poolAddress] = leveragePoolBalance[_poolAddress].sub( _stblLostAmount ); } else if (poolType == PoolType.REINSURANCE) { reinsurancePoolBalance = reinsurancePoolBalance.sub(_stblLostAmount); } if (_lostPercentage > 0) { virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.sub(_stblLostAmount); } } /// @notice Fullfils policybook claims by transfering the balance to claimer /// @param _claimer, address of the claimer recieving the withdraw /// @param _stblClaimAmount uint256 amount to of the claim function fundClaim( address _claimer, uint256 _stblClaimAmount, address _policyBookAddress ) external override onlyClaimingRegistry returns (uint256 _actualAmount) { _actualAmount = _withdrawFromLiquidityCushion(_claimer, _stblClaimAmount); _dispatchLiquidities( _policyBookAddress, DecimalsConverter.convertTo18(_actualAmount, stblDecimals) ); } function _dispatchLiquidities(address _policyBookAddress, uint256 _claimAmount) internal { IPolicyBook policyBook = IPolicyBook(_policyBookAddress); IPolicyBookFacade policyBookFacade = policyBook.policyBookFacade(); uint256 totalCoveragedLiquidity = policyBook.totalLiquidity(); uint256 totalLeveragedLiquidity = policyBookFacade.totalLeveragedLiquidity(); uint256 totalPoolLiquidity = totalCoveragedLiquidity.add(totalLeveragedLiquidity); // COVERAGE CONTRIBUTION uint256 coverageContribution = totalCoveragedLiquidity.mul(PERCENTAGE_100).div(totalPoolLiquidity); uint256 coverageLoss = _claimAmount.mul(coverageContribution).div(PERCENTAGE_100); _updatePoolLiquidity(_policyBookAddress, coverageLoss, 0, PoolType.COVERAGE); // LEVERAGE CONTRIBUTION address[] memory _userLeverageArr = policyBookFacade.listUserLeveragePools(0, policyBookFacade.countUserLeveragePools()); for (uint256 i = 0; i < _userLeverageArr.length; i++) { uint256 leverageContribution = policyBookFacade.LUuserLeveragePool(_userLeverageArr[i]).mul(PERCENTAGE_100).div( totalPoolLiquidity ); uint256 leverageLoss = _claimAmount.mul(leverageContribution).div(PERCENTAGE_100); _updatePoolLiquidity(_userLeverageArr[i], leverageLoss, 0, PoolType.LEVERAGE); } // REINSURANCE CONTRIBUTION uint256 reinsuranceContribution = (policyBookFacade.LUreinsurnacePool().add(policyBookFacade.VUreinsurnacePool())) .mul(PERCENTAGE_100) .div(totalPoolLiquidity); uint256 reinsuranceLoss = _claimAmount.mul(reinsuranceContribution).div(PERCENTAGE_100); _updatePoolLiquidity(address(reinsurancePool), reinsuranceLoss, 0, PoolType.REINSURANCE); } /// @notice Fullfils policybook claims by transfering the balance to claimer /// @param _voter, address of the voter recieving the withdraw /// @param _stblRewardAmount uint256 amount to of the reward function fundReward(address _voter, uint256 _stblRewardAmount) external override onlyClaimingRegistry returns (uint256 _actualAmount) { _actualAmount = _withdrawFromLiquidityCushion(_voter, _stblRewardAmount); _updatePoolLiquidity( address(reinsurancePool), DecimalsConverter.convertTo18(_actualAmount, stblDecimals), 0, PoolType.REINSURANCE ); } /// @notice Withdraws liquidity from a specific policbybook to the user /// @param _sender, address of the user beneficiary of the withdraw /// @param _stblAmount uint256 amount to be withdrawn function withdrawLiquidity( address _sender, uint256 _stblAmount, bool _isLeveragePool ) external override onlyPolicyBook broadcastBalancing returns (uint256 _actualAmount) { _actualAmount = _withdrawFromLiquidityCushion(_sender, _stblAmount); if (_isLeveragePool) { leveragePoolBalance[_msgSender()] = leveragePoolBalance[_msgSender()].sub( _actualAmount ); } else { regularCoverageBalance[_msgSender()] = regularCoverageBalance[_msgSender()].sub( _actualAmount ); } } function setMaintainer(address _newMainteiner) public onlyOwner { require(_newMainteiner != address(0), "CP: invalid maintainer address"); maintainer = _newMainteiner; } function pauseLiquidityCushionRebalancing(bool _paused) public onlyOwner { require(_paused != isLiqCushionPaused, "CP: invalid paused state"); isLiqCushionPaused = _paused; if (isLiqCushionPaused) { hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(liquidityCushionBalance); liquidityCushionBalance = 0; } } function automateHardRebalancing(bool _isAutomatic) public onlyOwner { require(_isAutomatic != automaticHardRebalancing, "CP: invalid state"); automaticHardRebalancing = _isAutomatic; } function allowDeployFundsToDefi(bool _deployFundsToDefi) public onlyOwner { require(_deployFundsToDefi != deployFundsToDefi, "CP: invalid input"); //can not disabled deploy funds to defi in case there is deposited amount if (!_deployFundsToDefi) { require(yieldGenerator.totalDeposit() == 0, "CP: Can't disable deploy funds"); } deployFundsToDefi = _deployFundsToDefi; // check isLiqCushionPaused isn't have the same state before update it if (isLiqCushionPaused != !deployFundsToDefi) { pauseLiquidityCushionRebalancing(!deployFundsToDefi); } } function _withdrawFromLiquidityCushion(address _sender, uint256 _stblAmount) internal broadcastBalancing returns (uint256 _actualAmount) { //withdraw from hardbalance if defi deployment is pasued if (!deployFundsToDefi) { require(hardUsdtAccumulatedBalance >= _stblAmount, "CP: insuficient liquidity"); hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.sub(_stblAmount); _actualAmount = _stblAmount; } else { //withdraw from liq cushion service if defi deployment is enabled require(!isLiqCushionPaused, "CP: withdraw is pasued"); if (_stblAmount > liquidityCushionBalance) { uint256 _diffAmount = _stblAmount.sub(liquidityCushionBalance); if (hardUsdtAccumulatedBalance >= _diffAmount) { hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.sub(_diffAmount); liquidityCushionBalance = liquidityCushionBalance.add(_diffAmount); } else if (hardUsdtAccumulatedBalance > 0) { liquidityCushionBalance = liquidityCushionBalance.add( hardUsdtAccumulatedBalance ); hardUsdtAccumulatedBalance = 0; } } require(liquidityCushionBalance > 0, "CP: insuficient liquidity"); _actualAmount = Math.min(_stblAmount, liquidityCushionBalance); liquidityCushionBalance = liquidityCushionBalance.sub(_actualAmount); } virtualUsdtAccumulatedBalance = virtualUsdtAccumulatedBalance.sub(_actualAmount); stblToken.safeTransfer(_sender, _actualAmount); } function _calcReinsurancePoolPremium(PremiumFactors memory factors) internal pure returns (uint256) { return (factors.premiumPerDeployment.mul(factors.vStblDeployedByRP).div(PRECISION)); } function _calcUserLeveragePoolPremium(PremiumFactors memory factors) internal { address[] memory _userLeverageArr = factors.policyBookFacade.listUserLeveragePools(0, factors.userLeveragePoolsCount); uint256 premium; uint256 _participatedLeverageAmount; for (uint256 i = 0; i < _userLeverageArr.length; i++) { _participatedLeverageAmount = clacParticipatedLeverageAmount( factors, _userLeverageArr[i] ); premium = ( factors.premiumPerDeployment.mul(_participatedLeverageAmount).div(PRECISION) ); leveragePoolBalance[_userLeverageArr[i]] = leveragePoolBalance[_userLeverageArr[i]] .add(premium); ILeveragePortfolio(_userLeverageArr[i]).addPolicyPremium( factors.epochsNumber, DecimalsConverter.convertTo18(premium, stblDecimals) ); } } function clacParticipatedLeverageAmount( PremiumFactors memory factors, address userLeveragePool ) internal view returns (uint256) { return DecimalsConverter .convertFrom18( factors.policyBookFacade.LUuserLeveragePool(userLeveragePool), stblDecimals ) .mul(leveragePortfolioView.calcM(factors.poolUtilizationRation, userLeveragePool)) .div(PERCENTAGE_100); } function _calcCoveragePoolPremium(PremiumFactors memory factors) internal pure returns (uint256) { return factors.premiumPerDeployment.mul(factors.vStblOfCP).div(PRECISION); } function getDepositAndWithdraw(uint256 _requiredLiquidity) internal view returns (uint256 deposit, uint256 withdraw) { uint256 _availableBalance = hardUsdtAccumulatedBalance.add(liquidityCushionBalance); if (_requiredLiquidity > _availableBalance) { withdraw = _requiredLiquidity.sub(_availableBalance); } else if (_requiredLiquidity < _availableBalance) { deposit = _availableBalance.sub(_requiredLiquidity); } } function getWithdrawPeriod() external view override returns (uint256) { return rebalanceDuration + ADDITIONAL_WITHDRAW_PERIOD; } }
rebalances pools acording to v2 specification and dao enforced policies emits PoolBalancesUpdatedcheck defi protocol balances hard rebalancing - Stop all withdrawals from all pools
function rebalanceLiquidityCushion() public override broadcastBalancing onlyMaintainer { require(!isLiqCushionPaused, "CP: liqudity cushion is pasued"); (, uint256 _lostAmount) = yieldGenerator.reevaluateDefiProtocolBalances(); if (_lostAmount > 0) { isLiqCushionPaused = true; if (automaticHardRebalancing) { defiHardRebalancing(); } } if (isLiqCushionPaused) { hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add(liquidityCushionBalance); liquidityCushionBalance = 0; return; } uint256 _pendingClaimAmount = claimingRegistry.getAllPendingClaimsAmount(); uint256 _pendingRewardAmount = claimingRegistry.getAllPendingRewardsAmount(); uint256 _pendingWithdrawlAmount = liquidityRegistry.getAllPendingWithdrawalRequestsAmount(); uint256 _requiredLiquidity = _pendingWithdrawlAmount.add(_pendingClaimAmount).add(_pendingRewardAmount); _requiredLiquidity = DecimalsConverter.convertFrom18(_requiredLiquidity, stblDecimals); (uint256 _deposit, uint256 _withdraw) = getDepositAndWithdraw(_requiredLiquidity); liquidityCushionBalance = _requiredLiquidity; hardUsdtAccumulatedBalance = 0; uint256 _actualAmount; if (_deposit > 0) { stblToken.safeApprove(address(yieldGenerator), 0); stblToken.safeApprove(address(yieldGenerator), _deposit); _actualAmount = yieldGenerator.deposit(_deposit); if (_actualAmount < _deposit) { hardUsdtAccumulatedBalance = hardUsdtAccumulatedBalance.add( (_deposit.sub(_actualAmount)) ); } _actualAmount = yieldGenerator.withdraw(_withdraw); if (_actualAmount < _withdraw) { liquidityCushionBalance = liquidityCushionBalance.sub( (_withdraw.sub(_actualAmount)) ); } } emit LiquidityCushionRebalanced(_requiredLiquidity, _withdraw, _deposit); }
5,401,317
pragma solidity ^0.4.24; import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; import 'zeppelin-solidity/contracts/lifecycle/Pausable.sol'; contract ImageUpload is Ownable, Pausable { // state variables address private _owner; // the contract creator struct image_info //structure to hold image information { string ipfshash; //image ipfshash string tag; // image tag as defined by the user uint256 timestamp; } struct images_owner { //struct used to link the user to all his uploaded images uint256[] ImagesId; } uint256 private _imagesCounter; // variable to track the count of images created // mapping definitions mapping (uint256 => address) private _ownerof; // will be used to verify the owner of any giving image id mapping (uint256 => image_info) private _ImgID; // this mapping to link each image information to its id mapping (address => images_owner) private _ownerImgIDs; // mapping to link the user address to all his Images Id // event definitions event CreateImage(address indexed _from, string _ipfs, string _tag, uint256 _id); constructor() public { //smart contract constructor _owner = msg.sender; _imagesCounter = 0; } // functionalities function createImage(string _ipfs, string _tag) public whenNotPaused() { uint256 _img_id; // image id require(_ownerof[_imagesCounter] == address(0),"ID already exist!"); // this to verify this id not used before _img_id = _imagesCounter; // unique image id _imagesCounter += 1; // increment imagecounter for next image upload image_info memory NewImage = image_info(_ipfs, _tag, block.timestamp); // memory image object created _ImgID[_img_id] = NewImage; // push new image to blockchain _ownerImgIDs[msg.sender].ImagesId.push(_img_id); // mapping new imageid to the user uploaded its _ownerof[_img_id] = msg.sender; // keep track the owner of each individual image uploaded id emit CreateImage(msg.sender,_ipfs,_tag,_img_id); // this event to log successful creation } function getImage(uint256 _img_id) public view returns (string, string, uint256) { // get specific image information require(_ownerof[_img_id] != address(0),"Image doesn't exist!"); image_info memory Image_info; Image_info = _ImgID[_img_id]; return (Image_info.ipfshash, Image_info.tag, Image_info.timestamp); } function getImages() public view returns (uint256[]) { // get all images ids for the msg sender address _user; _user = msg.sender; return _ownerImgIDs[_user].ImagesId; } function kill() public onlyOwner { // only owner can destruct the contract selfdestruct(owner); } }
get specific image information
function getImage(uint256 _img_id) public view returns (string, string, uint256) {
5,430,029
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol"; import "./Token.sol"; /** * @title BAPEToken contract * @dev Extends my ERC20 */ contract BAPEToken is Token { constructor(address _nftAddress) Token("Bored Ape Token", "BAPE", _nftAddress) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Token contract * @dev Extends ERC20 Token Standard basic implementation */ contract Token is ERC20, Ownable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; // Address of NFT Smart contract. Only owners of this NFT can claim tokens address public nftAddress; // How much tokens can be claimed by one address (10k) uint256 public constant TOKENS_PER_ADDRESS = 10000 * (10 ** 18); // Mapping if tokens for certain NFT ID has already been claimed mapping (uint256 => bool) private _claimedNfts; // Addresses that were claimed tokens EnumerableSet.AddressSet private _claimedOwners; // Airdrop will be active for 1 month bool public isAirdropActive = true; constructor(string memory name, string memory symbol, address _nftAddress) ERC20(name, symbol) { nftAddress = _nftAddress; } /** * @dev Pause airdrop if active, make active if paused */ function flipAirdropState() public onlyOwner { isAirdropActive = !isAirdropActive; } /** * @dev Returns if tokens for certain NFT ID has already been claimed */ function isTokensForNftClaimed(uint256 nftId) public view returns (bool) { return _claimedNfts[nftId]; } /** * @dev Returns if `owner` address has already claimed tokens */ function isOwnerClaimedTokens(address owner) public view returns (bool) { return _claimedOwners.contains(owner); } /** * @dev Returns number of NFTs in `owner`'s account. */ function nftBalanceOf(address owner) public view returns (uint256) { return IERC721Enumerable(nftAddress).balanceOf(owner); } /** * @dev Check if an `owner` address can claim tokens * Only the frontend calls this function just to display that a user can claim */ function canClaim(address owner) external view returns (bool) { // one address can claim only once if (isOwnerClaimedTokens(owner) == true || isAirdropActive == false) { return false; } bool _canOwnerClaim = false; uint256 nftsNumber = nftBalanceOf(owner); for (uint i = 0; i < nftsNumber; i++) { uint256 currentNftId = IERC721Enumerable(nftAddress).tokenOfOwnerByIndex(owner, i); if (isTokensForNftClaimed(currentNftId) == false) { _canOwnerClaim = true; } } return _canOwnerClaim; } /** * @dev The same as the external `canClaim()` but also sets `_claimedNfts`=true for all NFTs * and add an `owner` address to `_claimedOwners` * This function can be called only by `claim()` * * Duplicate code is required to save gas; otherwise, we need to iterate NFTs twice: * The first time is to call the external `canClaim()` * (i.e. check if an `owner` address can claim tokens) * The second is to update `_claimedNfts` and `_claimedOwners` */ function _canClaim(address owner) internal returns (bool) { // one address can claim only once if (isOwnerClaimedTokens(owner) == true) { return false; } bool _canOwnerClaim = false; uint256 nftsNumber = nftBalanceOf(owner); for (uint i = 0; i < nftsNumber; i++) { uint256 currentNftId = IERC721Enumerable(nftAddress).tokenOfOwnerByIndex(owner, i); if (isTokensForNftClaimed(currentNftId) == false) { _canOwnerClaim = true; _claimedNfts[currentNftId] = true; } } if (_canOwnerClaim == true) { _claimedOwners.add(owner); } return _canOwnerClaim; } /** * @dev Claim tokens */ function claim() public returns (bool) { require(isAirdropActive == true, "Airdrop is finished"); bool canSenderClaim = _canClaim(msg.sender); require(canSenderClaim == true, "Sender cannot claim"); _mint(msg.sender, TOKENS_PER_ADDRESS); return canSenderClaim; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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.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.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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 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)); } }
Claim tokens/
function claim() public returns (bool) { require(isAirdropActive == true, "Airdrop is finished"); bool canSenderClaim = _canClaim(msg.sender); require(canSenderClaim == true, "Sender cannot claim"); _mint(msg.sender, TOKENS_PER_ADDRESS); return canSenderClaim; }
366,458
pragma solidity ^0.5.8; library SafeMath { function MUL38(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV634(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function SUB406(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function ADD700(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } } contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED30(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = 0xfc0281163cFeDA9FbB3B18A72A27310B1725fD65; emit OWNERSHIPTRANSFERRED30(address(0), _owner); } function OWNER975() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER510() { //inject NONSTANDARD NAMING require(ISOWNER350(), "Ownable: caller is not the owner"); _; } function ISOWNER350() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP332() public ONLYOWNER510 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED30(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP193(address newOwner) public ONLYOWNER510 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP229(newOwner); } function _TRANSFEROWNERSHIP229(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED30(_owner, newOwner); _owner = newOwner; } } interface IERC20 { function TRANSFER697(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE20(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM431(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY947() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF859(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE181(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER948(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL469(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY947() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF859(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE181(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function TRANSFER697(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER167(msg.sender, to, value); return true; } function APPROVE20(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE409(msg.sender, spender, value); return true; } function TRANSFERFROM431(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER167(from, to, value); _APPROVE409(from, msg.sender, _allowances[from][msg.sender].SUB406(value)); return true; } function INCREASEALLOWANCE260(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE409(msg.sender, spender, _allowances[msg.sender][spender].ADD700(addedValue)); return true; } function DECREASEALLOWANCE155(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE409(msg.sender, spender, _allowances[msg.sender][spender].SUB406(subtractedValue)); return true; } function _TRANSFER167(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _balances[from] = _balances[from].SUB406(value); _balances[to] = _balances[to].ADD700(value); emit TRANSFER948(from, to, value); } function _MINT833(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD700(value); _balances[account] = _balances[account].ADD700(value); emit TRANSFER948(address(0), account, value); } function _APPROVE409(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit APPROVAL469(owner, spender, value); } } contract CSCToken is ERC20, Ownable { using SafeMath for uint256; string public constant name863 = "Crypto Service Capital Token"; //inject NONSTANDARD NAMING string public constant symbol721 = "CSCT"; //inject NONSTANDARD NAMING uint8 public constant decimals85 = 18; //inject NONSTANDARD NAMING bool public mintingFinished = false; mapping (address => bool) private _minters; event MINT126(address indexed to, uint256 amount); //inject NONSTANDARD NAMING event MINTFINISHED370(); //inject NONSTANDARD NAMING modifier CANMINT211() { //inject NONSTANDARD NAMING require(!mintingFinished); _; } function ISMINTER256(address minter) public view returns (bool) { //inject NONSTANDARD NAMING if (OWNER975() == minter) { return true; } return _minters[minter]; } modifier ONLYMINTER211() { //inject NONSTANDARD NAMING require(ISMINTER256(msg.sender), "Minter: caller is not the minter"); _; } function ADDMINTER63(address _minter) external ONLYOWNER510 returns (bool) { //inject NONSTANDARD NAMING require(_minter != address(0)); _minters[_minter] = true; return true; } function REMOVEMINTER886(address _minter) external ONLYOWNER510 returns (bool) { //inject NONSTANDARD NAMING require(_minter != address(0)); _minters[_minter] = false; return true; } function MINT259(address to, uint256 value) public ONLYMINTER211 returns (bool) { //inject NONSTANDARD NAMING _MINT833(to, value); emit MINT126(to, value); return true; } function FINISHMINTING196() ONLYOWNER510 CANMINT211 external returns (bool) { //inject NONSTANDARD NAMING mintingFinished = true; emit MINTFINISHED370(); return true; } } contract Crowdsale is Ownable { using SafeMath for uint256; uint256 public constant rate431 = 1000; // How many token units a buyer gets per wei //inject NONSTANDARD NAMING uint256 public constant cap376 = 10000 ether; // Maximum amount of funds //inject NONSTANDARD NAMING bool public isFinalized = false; // End timestamps where investments are allowed uint256 public startTime = 1559347199; // 31-May-19 23:59:59 UTC uint256 public endTime = 1577836799; // 30-Dec-19 23:59:59 UTC CSCToken public token; // CSCT token itself address payable public wallet = 0x1524Aa69ef4BA327576FcF548f7dD14aEaC8CA18; // Wallet of funds uint256 public weiRaised; // Amount of raised money in wei uint256 public firstBonus = 30; // 1st bonus percentage uint256 public secondBonus = 50; // 2nd bonus percentage event TOKENPURCHASE96(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //inject NONSTANDARD NAMING event FINALIZED531(); //inject NONSTANDARD NAMING constructor (CSCToken _CSCT) public { assert(address(_CSCT) != address(0)); token = _CSCT; } function () external payable { BUYTOKENS779(msg.sender); } // @return true if the transaction can buy tokens function VALIDPURCHASE868() internal view returns (bool) { //inject NONSTANDARD NAMING require(!token.mintingFinished()); require(weiRaised <= cap376); require(now >= startTime); require(now <= endTime); require(msg.value >= 0.001 ether); return true; } function TOKENSFORWEI360(uint weiAmount) public view returns (uint tokens) { //inject NONSTANDARD NAMING tokens = weiAmount.MUL38(rate431); tokens = tokens.ADD700(GETBONUS366(tokens, weiAmount)); } function GETBONUS366(uint256 _tokens, uint256 _weiAmount) public view returns (uint256) { //inject NONSTANDARD NAMING if (_weiAmount >= 30 ether) { return _tokens.MUL38(secondBonus).DIV634(100); } return _tokens.MUL38(firstBonus).DIV634(100); } function BUYTOKENS779(address beneficiary) public payable { //inject NONSTANDARD NAMING require(beneficiary != address(0)); require(VALIDPURCHASE868()); uint256 weiAmount = msg.value; uint256 tokens = TOKENSFORWEI360(weiAmount); weiRaised = weiRaised.ADD700(weiAmount); token.MINT259(beneficiary, tokens); emit TOKENPURCHASE96(msg.sender, beneficiary, weiAmount, tokens); wallet.transfer(msg.value); } function SETFIRSTBONUS839(uint256 _newBonus) ONLYOWNER510 external { //inject NONSTANDARD NAMING firstBonus = _newBonus; } function SETSECONDBONUS714(uint256 _newBonus) ONLYOWNER510 external { //inject NONSTANDARD NAMING secondBonus = _newBonus; } function CHANGEENDTIME347(uint256 _newTime) ONLYOWNER510 external { //inject NONSTANDARD NAMING require(endTime >= now); endTime = _newTime; } // Calls the contract's finalization function. function FINALIZE617() ONLYOWNER510 external { //inject NONSTANDARD NAMING require(!isFinalized); endTime = now; isFinalized = true; emit FINALIZED531(); } // @return true if crowdsale event has ended function HASENDED686() external view returns (bool) { //inject NONSTANDARD NAMING return now > endTime; } }
inject NONSTANDARD NAMING
function ALLOWANCE181(address owner, address spender) external view returns (uint256);
14,049,145
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; import "./interfaces/marketManagerInterface.sol"; import "./interfaces/interestModelInterface.sol"; import "./interfaces/marketHandlerDataStorageInterface.sol"; import "./interfaces/marketSIHandlerDataStorageInterface.sol"; import "./Errors.sol"; /** * @title Bifi user request proxy (navtive coin) * @notice access logic contracts via delegate calls. * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract coinProxy is RequestProxyErrors { /* handler storage */ address payable owner; uint256 handlerID; string tokenName = "ether"; uint256 constant unifiedPoint = 10 ** 18; marketManagerInterface marketManager; interestModelInterface interestModelInstance; marketHandlerDataStorageInterface handlerDataStorage; marketSIHandlerDataStorageInterface SIHandlerDataStorage; /* proxy storage */ address public handler; address public SI; string DEPOSIT = "deposit(uint256,bool)"; string REDEEM = "withdraw(uint256,bool)"; string BORROW = "borrow(uint256,bool)"; string REPAY = "repay(uint256,bool)"; modifier onlyOwner { require(msg.sender == owner, ONLY_OWNER); _; } modifier onlyMarketManager { address msgSender = msg.sender; require((msgSender == address(marketManager)) || (msgSender == owner), ONLY_MANAGER); _; } /** * @dev Construct a new coinProxy which uses coinHandlerLogic */ constructor () public { owner = msg.sender; } /** * @dev Replace the owner of the handler * @param _owner the address of the new owner * @return true (TODO: validate results) */ function ownershipTransfer(address _owner) onlyOwner external returns (bool) { owner = address(uint160(_owner)); return true; } /** * @dev Initialize the contract * @param _handlerID ID of handler * @param marketManagerAddr The address of market manager * @param interestModelAddr The address of handler interest model contract address * @param marketDataStorageAddr The address of handler data storage * @param siHandlerAddr The address of service incentive contract * @param SIHandlerDataStorageAddr The address of service incentive data storage */ function initialize(uint256 _handlerID, address handlerAddr, address marketManagerAddr, address interestModelAddr, address marketDataStorageAddr, address siHandlerAddr, address SIHandlerDataStorageAddr) onlyOwner public returns (bool) { handlerID = _handlerID; handler = handlerAddr; SI = siHandlerAddr; marketManager = marketManagerInterface(marketManagerAddr); interestModelInstance = interestModelInterface(interestModelAddr); handlerDataStorage = marketHandlerDataStorageInterface(marketDataStorageAddr); SIHandlerDataStorage = marketSIHandlerDataStorageInterface(SIHandlerDataStorageAddr); } /** * @dev Set ID of handler * @param _handlerID The ID of handler * @return true (TODO: validate results) */ function setHandlerID(uint256 _handlerID) onlyOwner public returns (bool) { handlerID = _handlerID; return true; } /** * @dev Set the address of handler * @param handlerAddr The address of handler * @return true (TODO: validate results) */ function setHandlerAddr(address handlerAddr) onlyOwner public returns (bool) { handler = handlerAddr; return true; } /** * @dev Set the address of service incentive contract * @param siHandlerAddr The address of service incentive contract * @return true (TODO: validate results) */ function setSiHandlerAddr(address siHandlerAddr) onlyOwner public returns (bool) { SI = siHandlerAddr; return true; } /** * @dev Get ID of handler * @return The connected handler ID */ function getHandlerID() public view returns (uint256) { return handlerID; } /** * @dev Get the address of handler * @return The handler address */ function getHandlerAddr() public view returns (address) { return handler; } /** * @dev Get the address of service incentive contract * @return The service incentive contract address */ function getSiHandlerAddr() public view returns (address) { return SI; } /** * @dev Move assets to sender for the migration event. */ function migration(address payable target) onlyOwner public returns (bool) { target.transfer(address(this).balance); /*ToDo: update selfDestruct function */ } /** * @dev fallback function where handler can receive native coin */ fallback () external payable { } /** * @dev Forward the request for deposit to the handler logic contract. * @param unifiedTokenAmount The amount of coins to deposit * @param flag Flag for the full calculation mode * @return whether the deposit has been made successfully or not. */ function deposit(uint256 unifiedTokenAmount, bool flag) public payable returns (bool) { bool result; bytes memory returnData; bytes memory data = abi.encodeWithSignature(DEPOSIT, unifiedTokenAmount, flag); (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return result; } /** * @dev Forward the request for withdraw to the handler logic contract. * @param unifiedTokenAmount The amount of coins to withdraw * @param flag Flag for the full calculation mode * @return whether the withdraw has been made successfully or not. */ function withdraw(uint256 unifiedTokenAmount, bool flag) public returns (bool) { bool result; bytes memory returnData; bytes memory data = abi.encodeWithSignature(REDEEM, unifiedTokenAmount, flag); (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return result; } /** * @dev Forward the request for borrow to the handler logic contract. * @param unifiedTokenAmount The amount of coins to borrow * @param flag Flag for the full calculation mode * @return whether the borrow has been made successfully or not. */ function borrow(uint256 unifiedTokenAmount, bool flag) public returns (bool) { bool result; bytes memory returnData; bytes memory data = abi.encodeWithSignature(BORROW, unifiedTokenAmount, flag); (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return result; } /** * @dev Forward the request for repay to the handler logic contract. * @param unifiedTokenAmount The amount of coins to repay * @param flag Flag for the full calculation mode * @return whether the repay has been made successfully or not. */ function repay(uint256 unifiedTokenAmount, bool flag) public payable returns (bool) { bool result; bytes memory returnData; bytes memory data = abi.encodeWithSignature(REPAY, unifiedTokenAmount, flag); (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return result; } /** * @dev Call other functions in handler logic contract. * @param data The encoded value of the function and argument * @return The result of the call */ function handlerProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return (result, returnData); } /** * @dev Call other view functions in handler logic contract. * (delegatecall does not work for view functions) * @param data The encoded value of the function and argument * @return The result of the call */ function handlerViewProxy(bytes memory data) external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return (result, returnData); } /** * @dev Call other functions in service incentive logic contract. * @param data The encoded value of the function and argument * @return The result of the call */ function siProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = SI.delegatecall(data); require(result, string(returnData)); return (result, returnData); } /** * @dev Call other view functions in service incentive logic contract. * (delegatecall does not work for view functions) * @param data The encoded value of the function and argument * @return The result of the call */ function siViewProxy(bytes memory data) external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = SI.delegatecall(data); require(result, string(returnData)); return (result, returnData); } }
Call other functions in handler logic contract. data The encoded value of the function and argument return The result of the call/
function handlerProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return (result, returnData); }
995,221
// File: contracts/interfaces/ISaffronBase.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; interface ISaffronBase { enum Tranche {S, AA, A} enum LPTokenType {dsec, principal} // Store values (balances, dsec, vdsec) with TrancheUint256 struct TrancheUint256 { uint256 S; uint256 AA; uint256 A; } struct epoch_params { uint256 start_date; // Time when the platform launched uint256 duration; // Duration of epoch } } // File: contracts/interfaces/ISaffronStrategy.sol pragma solidity ^0.7.1; interface ISaffronStrategy is ISaffronBase{ function deploy_all_capital() external; function select_adapter_for_liquidity_removal() external returns(address); function add_adapter(address adapter_address) external; function add_pool(address pool_address) external; function delete_adapters() external; function set_governance(address to) external; function get_adapter_address(uint256 adapter_index) external view returns(address); function set_pool_SFI_reward(uint256 poolIndex, uint256 reward) external; } // File: contracts/interfaces/ISaffronPool.sol pragma solidity ^0.7.1; interface ISaffronPool is ISaffronBase { function add_liquidity(uint256 amount, Tranche tranche) external; function remove_liquidity(address v1_dsec_token_address, uint256 dsec_amount, address v1_principal_token_address, uint256 principal_amount) external; function get_base_asset_address() external view returns(address); function hourly_strategy(address adapter_address) external; function wind_down_epoch(uint256 epoch, uint256 amount_sfi) external; function set_governance(address to) external; function get_epoch_cycle_params() external view returns (uint256, uint256); function shutdown() external; } // File: contracts/interfaces/ISaffronAdapter.sol pragma solidity ^0.7.1; interface ISaffronAdapter is ISaffronBase { function deploy_capital(uint256 amount) external; function return_capital(uint256 base_asset_amount, address to) external; function approve_transfer(address addr,uint256 amount) external; function get_base_asset_address() external view returns(address); function set_base_asset(address addr) external; function get_holdings() external returns(uint256); function get_interest(uint256 principal) external returns(uint256); function set_governance(address to) external; } // File: contracts/lib/SafeMath.sol pragma solidity ^0.7.1; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/lib/IERC20.sol pragma solidity ^0.7.1; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/lib/Context.sol pragma solidity ^0.7.1; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/lib/Address.sol pragma solidity ^0.7.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ 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.3._ */ 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.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/lib/ERC20.sol pragma solidity ^0.7.1; /** * @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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/lib/SafeERC20.sol pragma solidity ^0.7.1; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/SFI.sol pragma solidity ^0.7.1; contract SFI is ERC20 { using SafeERC20 for IERC20; address public governance; address public SFI_minter; uint256 public MAX_TOKENS = 100000 ether; constructor (string memory name, string memory symbol) ERC20(name, symbol) { // Initial governance is Saffron Deployer governance = msg.sender; } function mint_SFI(address to, uint256 amount) public { require(msg.sender == SFI_minter, "must be SFI_minter"); require(this.totalSupply() + amount < MAX_TOKENS, "cannot mint more than MAX_TOKENS"); _mint(to, amount); } function set_minter(address to) external { require(msg.sender == governance, "must be governance"); SFI_minter = to; } function set_governance(address to) external { require(msg.sender == governance, "must be governance"); governance = to; } event ErcSwept(address who, address to, address token, uint256 amount); function erc_sweep(address _token, address _to) public { require(msg.sender == governance, "must be governance"); IERC20 tkn = IERC20(_token); uint256 tBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, tBal); emit ErcSwept(msg.sender, _to, _token, tBal); } } // File: contracts/SaffronLPBalanceToken.sol pragma solidity ^0.7.1; contract SaffronLPBalanceToken is ERC20 { address public pool_address; constructor (string memory name, string memory symbol) ERC20(name, symbol) { // Set pool_address to saffron pool that created token pool_address = msg.sender; } // Allow creating new tranche tokens function mint(address to, uint256 amount) public { require(msg.sender == pool_address, "must be pool"); _mint(to, amount); } function burn(address account, uint256 amount) public { require(msg.sender == pool_address, "must be pool"); _burn(account, amount); } function set_governance(address to) external { require(msg.sender == pool_address, "must be pool"); pool_address = to; } } // File: contracts/SaffronPool.sol pragma solidity ^0.7.1; contract SaffronPool is ISaffronPool { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; // Governance (v3: add off-chain/on-chain governance) address public base_asset_address; // Base asset managed by the pool (DAI, USDT, YFI...) address public SFI_address; // SFI token uint256 public pool_principal; // Current principal balance (added minus removed) uint256 public pool_interest; // Current interest balance (redeemable by dsec tokens) uint256 public tranche_A_multiplier; // Current yield multiplier for tranche A uint256 public SFI_ratio; // Ratio of base asset to SFI necessary to join tranche A bool public _shutdown = false; // v0, v1: shutdown the pool after the final capital deploy to prevent burning funds /**** ADAPTERS ****/ address public best_adapter_address; // Current best adapter selected by strategy uint256 public adapter_total_principal; // v0, v1: only one adapter ISaffronAdapter[] private adapters; // v2: list of adapters mapping(address=>uint256) private adapter_index; // v1: adapter contract address lookup for array indexes /**** STRATEGY ****/ address public strategy; /**** EPOCHS ****/ epoch_params public epoch_cycle = epoch_params({ start_date: 1604239200, // 11/01/2020 @ 2:00pm (UTC) duration: 14 days // 1210000 seconds }); /**** EPOCH INDEXED STORAGE ****/ uint256[] public epoch_principal; // Total principal owned by the pool (all tranches) mapping(uint256=>bool) public epoch_wound_down; // True if epoch has been wound down already (governance) /**** EPOCH-TRANCHE INDEXED STORAGE ****/ // Array of arrays, example: tranche_SFI_earned[epoch][Tranche.S] address[3][] public dsec_token_addresses; // Address for each dsec token address[3][] public principal_token_addresses; // Address for each principal token uint256[3][] public tranche_total_dsec; // Total dsec (tokens + vdsec) uint256[3][] public tranche_total_principal; // Total outstanding principal tokens uint256[3][] public tranche_total_utilized; // Total utilized balance in each tranche uint256[3][] public tranche_total_unutilized; // Total unutilized balance in each tranche uint256[3][] public tranche_S_virtual_utilized; // Total utilized virtual balance taken from tranche S (first index unused) uint256[3][] public tranche_S_virtual_unutilized; // Total unutilized virtual balance taken from tranche S (first index unused) uint256[3][] public tranche_interest_earned; // Interest earned (calculated at wind_down_epoch) uint256[3][] public tranche_SFI_earned; // Total SFI earned (minted at wind_down_epoch) /**** SFI GENERATION ****/ // v0: pool generates SFI based on subsidy schedule // v1: pool is distributed SFI generated by the strategy contract // v1: pools each get an amount of SFI generated depending on the total liquidity added within each interval TrancheUint256 public TRANCHE_SFI_MULTIPLIER = TrancheUint256({ S: 90000, AA: 0, A: 10000 }); /**** TRANCHE BALANCES ****/ // (v0 & v1: epochs are hard-forks) // (v2: epoch rollover implemented) // TrancheUint256 private eternal_unutilized_balances; // Unutilized balance (in base assets) for each tranche (assets held in this pool + assets held in platforms) // TrancheUint256 private eternal_utilized_balances; // Balance for each tranche that is not held within this pool but instead held on a platform via an adapter /**** SAFFRON LP TOKENS ****/ // If we just have a token address then we can look up epoch and tranche balance tokens using a mapping(address=>SaffronLPdsecInfo) // LP tokens are dsec (redeemable for interest+SFI) and principal (redeemable for base asset) tokens struct SaffronLPTokenInfo { bool exists; uint256 epoch; Tranche tranche; LPTokenType token_type; } mapping(address=>SaffronLPTokenInfo) private saffron_LP_token_info; constructor(address _strategy, address _base_asset, address _SFI_address, uint256 _SFI_ratio, bool epoch_cycle_reset) { governance = msg.sender; base_asset_address = _base_asset; strategy = _strategy; SFI_address = _SFI_address; tranche_A_multiplier = 10; // v1: start enhanced yield at 10X SFI_ratio = _SFI_ratio; // v1: constant ratio epoch_cycle.duration = (epoch_cycle_reset ? 20 minutes : 14 days); // Make testing previous epochs easier epoch_cycle.start_date = (epoch_cycle_reset ? (block.timestamp) - (4 * epoch_cycle.duration) : 1604239200); // Make testing previous epochs easier } function new_epoch(uint256 epoch, address[] memory saffron_LP_dsec_token_addresses, address[] memory saffron_LP_principal_token_addresses) public { require(tranche_total_principal.length == epoch, "improper new epoch"); require(governance == msg.sender, "must be governance"); epoch_principal.push(0); tranche_total_dsec.push([0,0,0]); tranche_total_principal.push([0,0,0]); tranche_total_utilized.push([0,0,0]); tranche_total_unutilized.push([0,0,0]); tranche_S_virtual_utilized.push([0,0,0]); tranche_S_virtual_unutilized.push([0,0,0]); tranche_interest_earned.push([0,0,0]); tranche_SFI_earned.push([0,0,0]); dsec_token_addresses.push([ // Address for each dsec token saffron_LP_dsec_token_addresses[uint256(Tranche.S)], saffron_LP_dsec_token_addresses[uint256(Tranche.AA)], saffron_LP_dsec_token_addresses[uint256(Tranche.A)] ]); principal_token_addresses.push([ // Address for each principal token saffron_LP_principal_token_addresses[uint256(Tranche.S)], saffron_LP_principal_token_addresses[uint256(Tranche.AA)], saffron_LP_principal_token_addresses[uint256(Tranche.A)] ]); // Token info for looking up epoch and tranche of dsec tokens by token contract address saffron_LP_token_info[saffron_LP_dsec_token_addresses[uint256(Tranche.S)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.S, token_type: LPTokenType.dsec }); saffron_LP_token_info[saffron_LP_dsec_token_addresses[uint256(Tranche.AA)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.AA, token_type: LPTokenType.dsec }); saffron_LP_token_info[saffron_LP_dsec_token_addresses[uint256(Tranche.A)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.A, token_type: LPTokenType.dsec }); // for looking up epoch and tranche of PRINCIPAL tokens by token contract address saffron_LP_token_info[saffron_LP_principal_token_addresses[uint256(Tranche.S)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.S, token_type: LPTokenType.principal }); saffron_LP_token_info[saffron_LP_principal_token_addresses[uint256(Tranche.AA)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.AA, token_type: LPTokenType.principal }); saffron_LP_token_info[saffron_LP_principal_token_addresses[uint256(Tranche.A)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.A, token_type: LPTokenType.principal }); } struct BalanceVars { // Tranche balance uint256 deposit; // User deposit uint256 capacity; // Capacity for user's intended tranche uint256 change; // Change from deposit - capacity // S tranche specific vars uint256 consumed; // Total consumed uint256 utilized_consumed; uint256 unutilized_consumed; uint256 available_utilized; uint256 available_unutilized; } event TrancheBalance(uint256 tranche, uint256 amount, uint256 deposit, uint256 capacity, uint256 change, uint256 consumed, uint256 utilized_consumed, uint256 unutilized_consumed, uint256 available_utilized, uint256 available_unutilized); event DsecGeneration(uint256 time_remaining, uint256 amount, uint256 dsec, address dsec_address, uint256 epoch, uint256 tranche, address user_address, address principal_token_addr); event AddLiquidity(uint256 new_pool_principal, uint256 new_epoch_principal, uint256 new_eternal_balance, uint256 new_tranche_principal, uint256 new_tranche_dsec); // LP user adds liquidity to the pool // Pre-requisite (front-end): have user approve transfer on front-end to base asset using our contract address function add_liquidity(uint256 amount, Tranche tranche) external override { require(!_shutdown, "pool shutdown"); require(tranche == Tranche.S || tranche == Tranche.A, "v1: can't add_liquidity into AA tranche"); uint256 epoch = get_current_epoch(); require(amount != 0, "can't add 0"); require(epoch == 10, "v1.10: must be epoch 10 only"); BalanceVars memory bv = BalanceVars({ deposit: 0, capacity: 0, change: 0, consumed: 0, utilized_consumed: 0, unutilized_consumed: 0, available_utilized: 0, available_unutilized: 0 }); (bv.available_utilized, bv.available_unutilized) = get_available_S_balances(); if (tranche == Tranche.S) { tranche_total_unutilized[epoch][uint256(Tranche.S)] = tranche_total_unutilized[epoch][uint256(Tranche.S)].add(amount); bv.deposit = amount; } // if (tranche == Tranche.AA) {} // v1: AA tranche disabled (S tranche is effectively AA) if (tranche == Tranche.A) { // Find capacity for S tranche to facilitate a deposit into A. Deposit is min(principal, capacity): restricted by the user's capital or S tranche capacity bv.capacity = (bv.available_utilized.add(bv.available_unutilized)).div(tranche_A_multiplier); bv.deposit = (amount < bv.capacity) ? amount : bv.capacity; bv.consumed = bv.deposit.mul(tranche_A_multiplier); if (bv.consumed <= bv.available_utilized) { // Take capacity from tranche S utilized first and give virtual utilized balance to AA bv.utilized_consumed = bv.consumed; } else { // Take capacity from tranche S utilized and tranche S unutilized and give virtual utilized/unutilized balances to AA bv.utilized_consumed = bv.available_utilized; bv.unutilized_consumed = bv.consumed.sub(bv.utilized_consumed); tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)].add(bv.unutilized_consumed); } tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)].add(bv.utilized_consumed); if (bv.deposit < amount) bv.change = amount.sub(bv.deposit); } // Calculate the dsec for deposited DAI uint256 dsec = bv.deposit.mul(get_seconds_until_epoch_end(epoch)); // Update pool principal eternal and epoch state pool_principal = pool_principal.add(bv.deposit); // Add DAI to principal totals epoch_principal[epoch] = epoch_principal[epoch].add(bv.deposit); // Add DAI total balance for epoch // Update dsec and principal balance state tranche_total_dsec[epoch][uint256(tranche)] = tranche_total_dsec[epoch][uint256(tranche)].add(dsec); tranche_total_principal[epoch][uint256(tranche)] = tranche_total_principal[epoch][uint256(tranche)].add(bv.deposit); // Transfer DAI from LP to pool IERC20(base_asset_address).safeTransferFrom(msg.sender, address(this), bv.deposit); if (tranche == Tranche.A) IERC20(SFI_address).safeTransferFrom(msg.sender, address(this), bv.deposit * 1 ether / SFI_ratio); // Mint Saffron LP epoch 1 tranche dsec tokens and transfer them to sender SaffronLPBalanceToken(dsec_token_addresses[epoch][uint256(tranche)]).mint(msg.sender, dsec); // Mint Saffron LP epoch 1 tranche principal tokens and transfer them to sender SaffronLPBalanceToken(principal_token_addresses[epoch][uint256(tranche)]).mint(msg.sender, bv.deposit); emit TrancheBalance(uint256(tranche), bv.deposit, bv.deposit, bv.capacity, bv.change, bv.consumed, bv.utilized_consumed, bv.unutilized_consumed, bv.available_utilized, bv.available_unutilized); emit DsecGeneration(get_seconds_until_epoch_end(epoch), bv.deposit, dsec, dsec_token_addresses[epoch][uint256(tranche)], epoch, uint256(tranche), msg.sender, principal_token_addresses[epoch][uint256(tranche)]); emit AddLiquidity(pool_principal, epoch_principal[epoch], 0, tranche_total_principal[epoch][uint256(tranche)], tranche_total_dsec[epoch][uint256(tranche)]); } event WindDownEpochSFI(uint256 previous_epoch, uint256 S_SFI, uint256 AA_SFI, uint256 A_SFI); event WindDownEpochState(uint256 epoch, uint256 tranche_S_interest, uint256 tranche_AA_interest, uint256 tranche_A_interest, uint256 tranche_SFI_earnings_S, uint256 tranche_SFI_earnings_AA, uint256 tranche_SFI_earnings_A); struct WindDownVars { uint256 previous_epoch; uint256 epoch_interest; uint256 epoch_dsec; uint256 tranche_A_interest_ratio; uint256 tranche_A_interest; uint256 tranche_S_interest; } function wind_down_epoch(uint256 epoch, uint256 amount_sfi) public override { require(msg.sender == strategy, "must be strategy"); require(!epoch_wound_down[epoch], "epoch already wound down"); uint256 current_epoch = get_current_epoch(); require(epoch < current_epoch, "cannot wind down future epoch"); WindDownVars memory wind_down = WindDownVars({ previous_epoch: 0, epoch_interest: 0, epoch_dsec: 0, tranche_A_interest_ratio: 0, tranche_A_interest: 0, tranche_S_interest: 0 }); wind_down.previous_epoch = current_epoch - 1; require(block.timestamp >= get_epoch_end(wind_down.previous_epoch), "can't call before epoch ended"); // Calculate SFI earnings per tranche tranche_SFI_earned[epoch][uint256(Tranche.S)] = TRANCHE_SFI_MULTIPLIER.S.mul(amount_sfi).div(100000); tranche_SFI_earned[epoch][uint256(Tranche.AA)] = TRANCHE_SFI_MULTIPLIER.AA.mul(amount_sfi).div(100000); tranche_SFI_earned[epoch][uint256(Tranche.A)] = TRANCHE_SFI_MULTIPLIER.A.mul(amount_sfi).div(100000); emit WindDownEpochSFI(wind_down.previous_epoch, tranche_SFI_earned[epoch][uint256(Tranche.S)], tranche_SFI_earned[epoch][uint256(Tranche.AA)], tranche_SFI_earned[epoch][uint256(Tranche.A)]); // Calculate interest earnings per tranche // Wind down will calculate interest and SFI earned by each tranche for the epoch which has ended // Liquidity cannot be removed until wind_down_epoch is called and epoch_wound_down[epoch] is set to true // Calculate pool_interest // v0, v1: we only have one adapter ISaffronAdapter adapter = ISaffronAdapter(best_adapter_address); wind_down.epoch_interest = adapter.get_interest(adapter_total_principal); pool_interest = pool_interest.add(wind_down.epoch_interest); // Total dsec // TODO: assert (dsec.totalSupply == epoch_dsec) wind_down.epoch_dsec = tranche_total_dsec[epoch][uint256(Tranche.S)].add(tranche_total_dsec[epoch][uint256(Tranche.A)]); wind_down.tranche_A_interest_ratio = tranche_total_dsec[epoch][uint256(Tranche.A)].mul(1 ether).div(wind_down.epoch_dsec); // Calculate tranche share of interest wind_down.tranche_A_interest = (wind_down.epoch_interest.mul(wind_down.tranche_A_interest_ratio).div(1 ether)).mul(tranche_A_multiplier); wind_down.tranche_S_interest = wind_down.epoch_interest.sub(wind_down.tranche_A_interest); // Update state for remove_liquidity tranche_interest_earned[epoch][uint256(Tranche.S)] = wind_down.tranche_S_interest; tranche_interest_earned[epoch][uint256(Tranche.AA)] = 0; tranche_interest_earned[epoch][uint256(Tranche.A)] = wind_down.tranche_A_interest; // Distribute SFI earnings to S tranche based on S tranche % share of dsec via vdsec emit WindDownEpochState(epoch, wind_down.tranche_S_interest, 0, wind_down.tranche_A_interest, uint256(tranche_SFI_earned[epoch][uint256(Tranche.S)]), uint256(tranche_SFI_earned[epoch][uint256(Tranche.AA)]), uint256(tranche_SFI_earned[epoch][uint256(Tranche.A)])); epoch_wound_down[epoch] = true; delete wind_down; } event RemoveLiquidityDsec(uint256 dsec_percent, uint256 interest_owned, uint256 SFI_owned); event RemoveLiquidityPrincipal(uint256 principal); function remove_liquidity(address dsec_token_address, uint256 dsec_amount, address principal_token_address, uint256 principal_amount) external override { require(dsec_amount > 0 || principal_amount > 0, "can't remove 0"); ISaffronAdapter best_adapter = ISaffronAdapter(best_adapter_address); uint256 interest_owned; uint256 SFI_earn; uint256 SFI_return; uint256 dsec_percent; // Update state for removal via dsec token if (dsec_token_address != address(0x0) && dsec_amount > 0) { // Get info about the v1 dsec token from its address and check that it exists SaffronLPTokenInfo memory token_info = saffron_LP_token_info[dsec_token_address]; require(token_info.exists, "balance token lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); // Token epoch must be a past epoch uint256 token_epoch = token_info.epoch; require(token_info.token_type == LPTokenType.dsec, "bad dsec address"); require(token_epoch == 10, "v1.10: bal token epoch must be 10"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); uint256 tranche_dsec = tranche_total_dsec[token_epoch][uint256(token_info.tranche)]; // Dsec gives user claim over a tranche's earned SFI and interest dsec_percent = (tranche_dsec == 0) ? 0 : dsec_amount.mul(1 ether).div(tranche_dsec); interest_owned = tranche_interest_earned[token_epoch][uint256(token_info.tranche)].mul(dsec_percent) / 1 ether; SFI_earn = tranche_SFI_earned[token_epoch][uint256(token_info.tranche)].mul(dsec_percent) / 1 ether; tranche_interest_earned[token_epoch][uint256(token_info.tranche)] = tranche_interest_earned[token_epoch][uint256(token_info.tranche)].sub(interest_owned); tranche_SFI_earned[token_epoch][uint256(token_info.tranche)] = tranche_SFI_earned[token_epoch][uint256(token_info.tranche)].sub(SFI_earn); tranche_total_dsec[token_epoch][uint256(token_info.tranche)] = tranche_total_dsec[token_epoch][uint256(token_info.tranche)].sub(dsec_amount); pool_interest = pool_interest.sub(interest_owned); } // Update state for removal via principal token if (principal_token_address != address(0x0) && principal_amount > 0) { // Get info about the v1 dsec token from its address and check that it exists SaffronLPTokenInfo memory token_info = saffron_LP_token_info[principal_token_address]; require(token_info.exists, "balance token info lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); // Token epoch must be a past epoch uint256 token_epoch = token_info.epoch; require(token_info.token_type == LPTokenType.principal, "bad balance token address"); require(token_epoch == 10, "v1.10: bal token epoch must be 10"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); tranche_total_principal[token_epoch][uint256(token_info.tranche)] = tranche_total_principal[token_epoch][uint256(token_info.tranche)].sub(principal_amount); epoch_principal[token_epoch] = epoch_principal[token_epoch].sub(principal_amount); pool_principal = pool_principal.sub(principal_amount); adapter_total_principal = adapter_total_principal.sub(principal_amount); if (token_info.tranche == Tranche.A) SFI_return = principal_amount * 1 ether / SFI_ratio; } // Transfer if (dsec_token_address != address(0x0) && dsec_amount > 0) { SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); sbt.burn(msg.sender, dsec_amount); if (interest_owned > 0) { best_adapter.return_capital(interest_owned, msg.sender); } IERC20(SFI_address).safeTransfer(msg.sender, SFI_earn); emit RemoveLiquidityDsec(dsec_percent, interest_owned, SFI_earn); } if (principal_token_address != address(0x0) && principal_amount > 0) { SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); sbt.burn(msg.sender, principal_amount); best_adapter.return_capital(principal_amount, msg.sender); IERC20(SFI_address).safeTransfer(msg.sender, SFI_return); emit RemoveLiquidityPrincipal(principal_amount); } require((dsec_token_address != address(0x0) && dsec_amount > 0) || (principal_token_address != address(0x0) && principal_amount > 0), "no action performed"); } // Strategy contract calls this to deploy capital to platforms event StrategicDeploy(address adapter_address, uint256 amount, uint256 epoch); function hourly_strategy(address adapter_address) external override { require(msg.sender == strategy, "must be strategy"); require(!_shutdown, "pool shutdown"); uint256 epoch = get_current_epoch(); best_adapter_address = adapter_address; ISaffronAdapter best_adapter = ISaffronAdapter(adapter_address); uint256 amount = IERC20(base_asset_address).balanceOf(address(this)); // Update utilized/unutilized epoch-tranche state tranche_total_utilized[epoch][uint256(Tranche.S)] = tranche_total_utilized[epoch][uint256(Tranche.S)].add(tranche_total_unutilized[epoch][uint256(Tranche.S)]); tranche_total_utilized[epoch][uint256(Tranche.A)] = tranche_total_utilized[epoch][uint256(Tranche.A)].add(tranche_total_unutilized[epoch][uint256(Tranche.A)]); tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)].add(tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)]); tranche_total_unutilized[epoch][uint256(Tranche.S)] = 0; tranche_total_unutilized[epoch][uint256(Tranche.A)] = 0; tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)] = 0; // Add principal to adapter total adapter_total_principal = adapter_total_principal.add(amount); emit StrategicDeploy(adapter_address, amount, epoch); // Move base assets to adapter and deploy IERC20(base_asset_address).safeTransfer(adapter_address, amount); best_adapter.deploy_capital(amount); } function shutdown() external override { require(msg.sender == strategy || msg.sender == governance, "must be strategy"); require(block.timestamp > get_epoch_end(1) - 1 days, "trying to shutdown too early"); _shutdown = true; } /*** GOVERNANCE ***/ function set_governance(address to) external override { require(msg.sender == governance, "must be governance"); governance = to; } function set_best_adapter(address to) external { require(msg.sender == governance, "must be governance"); best_adapter_address = to; } /*** TIME UTILITY FUNCTIONS ***/ function get_epoch_end(uint256 epoch) public view returns (uint256) { return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)); } function get_current_epoch() public view returns (uint256) { require(block.timestamp > epoch_cycle.start_date, "before epoch 0"); return (block.timestamp - epoch_cycle.start_date) / epoch_cycle.duration; } function get_seconds_until_epoch_end(uint256 epoch) public view returns (uint256) { return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)).sub(block.timestamp); } /*** GETTERS ***/ function get_available_S_balances() public view returns(uint256, uint256) { uint256 epoch = get_current_epoch(); uint256 AA_A_utilized = tranche_S_virtual_utilized[epoch][uint256(Tranche.A)].add(tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)]); uint256 AA_A_unutilized = tranche_S_virtual_unutilized[epoch][uint256(Tranche.A)].add(tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)]); uint256 S_utilized = tranche_total_utilized[epoch][uint256(Tranche.S)]; uint256 S_unutilized = tranche_total_unutilized[epoch][uint256(Tranche.S)]; return ((S_utilized > AA_A_utilized ? S_utilized - AA_A_utilized : 0), (S_unutilized > AA_A_unutilized ? S_unutilized - AA_A_unutilized : 0)); } function get_epoch_cycle_params() external view override returns (uint256, uint256) { return (epoch_cycle.start_date, epoch_cycle.duration); } function get_base_asset_address() external view override returns(address) { return base_asset_address; } //***** ADAPTER FUNCTIONS *****// // Delete adapters (v0: for v0 wind-down) function delete_adapters() external { require(msg.sender == governance, "must be governance"); require(block.timestamp > epoch_cycle.start_date + 10 weeks, "too soon"); delete adapters; } event ErcSwept(address who, address to, address token, uint256 amount); function erc_sweep(address _token, address _to) public { require(msg.sender == governance, "must be governance"); require(_token != base_asset_address && _token != SFI_address, "cannot sweep pool assets"); IERC20 tkn = IERC20(_token); uint256 tBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, tBal); emit ErcSwept(msg.sender, _to, _token, tBal); } event Swept(address who, address to, uint256 sfiBal, uint256 baseBal); function sweep(address _to) public { require(msg.sender == governance, "must be governance"); IERC20 tkn = IERC20(address(SFI_address)); uint256 sfiBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, sfiBal); IERC20 base = IERC20(address(base_asset_address)); uint256 baseBal = base.balanceOf(address(this)); base.safeTransfer(_to, baseBal); emit Swept(msg.sender, _to, sfiBal, baseBal); } }
LP user adds liquidity to the pool Pre-requisite (front-end): have user approve transfer on front-end to base asset using our contract address if (tranche == Tranche.AA) {} v1: AA tranche disabled (S tranche is effectively AA) Find capacity for S tranche to facilitate a deposit into A. Deposit is min(principal, capacity): restricted by the user's capital or S tranche capacity Take capacity from tranche S utilized first and give virtual utilized balance to AA Take capacity from tranche S utilized and tranche S unutilized and give virtual utilized/unutilized balances to AA
function add_liquidity(uint256 amount, Tranche tranche) external override { require(!_shutdown, "pool shutdown"); require(tranche == Tranche.S || tranche == Tranche.A, "v1: can't add_liquidity into AA tranche"); uint256 epoch = get_current_epoch(); require(amount != 0, "can't add 0"); require(epoch == 10, "v1.10: must be epoch 10 only"); BalanceVars memory bv = BalanceVars({ deposit: 0, capacity: 0, change: 0, consumed: 0, utilized_consumed: 0, unutilized_consumed: 0, available_utilized: 0, available_unutilized: 0 }); (bv.available_utilized, bv.available_unutilized) = get_available_S_balances(); if (tranche == Tranche.S) { tranche_total_unutilized[epoch][uint256(Tranche.S)] = tranche_total_unutilized[epoch][uint256(Tranche.S)].add(amount); bv.deposit = amount; } if (tranche == Tranche.A) { bv.capacity = (bv.available_utilized.add(bv.available_unutilized)).div(tranche_A_multiplier); bv.deposit = (amount < bv.capacity) ? amount : bv.capacity; bv.consumed = bv.deposit.mul(tranche_A_multiplier); if (bv.consumed <= bv.available_utilized) { bv.utilized_consumed = bv.consumed; bv.utilized_consumed = bv.available_utilized; bv.unutilized_consumed = bv.consumed.sub(bv.utilized_consumed); tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)].add(bv.unutilized_consumed); } tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)].add(bv.utilized_consumed); if (bv.deposit < amount) bv.change = amount.sub(bv.deposit); } tranche_total_principal[epoch][uint256(tranche)] = tranche_total_principal[epoch][uint256(tranche)].add(bv.deposit); if (tranche == Tranche.A) IERC20(SFI_address).safeTransferFrom(msg.sender, address(this), bv.deposit * 1 ether / SFI_ratio); emit TrancheBalance(uint256(tranche), bv.deposit, bv.deposit, bv.capacity, bv.change, bv.consumed, bv.utilized_consumed, bv.unutilized_consumed, bv.available_utilized, bv.available_unutilized); emit DsecGeneration(get_seconds_until_epoch_end(epoch), bv.deposit, dsec, dsec_token_addresses[epoch][uint256(tranche)], epoch, uint256(tranche), msg.sender, principal_token_addresses[epoch][uint256(tranche)]); emit AddLiquidity(pool_principal, epoch_principal[epoch], 0, tranche_total_principal[epoch][uint256(tranche)], tranche_total_dsec[epoch][uint256(tranche)]); } event WindDownEpochSFI(uint256 previous_epoch, uint256 S_SFI, uint256 AA_SFI, uint256 A_SFI); event WindDownEpochState(uint256 epoch, uint256 tranche_S_interest, uint256 tranche_AA_interest, uint256 tranche_A_interest, uint256 tranche_SFI_earnings_S, uint256 tranche_SFI_earnings_AA, uint256 tranche_SFI_earnings_A);
1,299,997
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; pragma abicoder v2; // import "hardhat/console.sol"; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./StakingV2.sol"; abstract contract InterfaceImpishDAO { function buyNFTPrice(uint256 tokenID) public view virtual returns (uint256); function buyNFT(uint256 tokenID) public virtual; function deposit() public payable virtual; } abstract contract IRWMarket { function acceptSellOffer(uint256 offerId) public payable virtual; } abstract contract ISpiralMarket { struct Listing { // What price is it listed for uint256 price; // The owner that listed it. If the owner has changed, it can't be sold anymore. address owner; } // Listing of all Tokens that are for sale mapping(uint256 => Listing) public forSale; function buySpiral(uint256 tokenId) external payable virtual; } abstract contract IWETH9 { function deposit() external payable virtual; function withdraw(uint256 amount) external virtual; function balanceOf(address owner) external virtual returns (uint256); } contract BuyWithEther is IERC721Receiver { // Uniswap v3router ISwapRouter public immutable swapRouter; // Contract addresses deployed on Arbitrum address public constant WETH9 = 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1; address public constant IMPISH = 0x36F6d831210109719D15abAEe45B327E9b43D6C6; address public constant RWNFT = 0x895a6F444BE4ba9d124F61DF736605792B35D66b; address public constant MAGIC = 0x539bdE0d7Dbd336b79148AA742883198BBF60342; address public constant IMPISHSPIRAL = 0xB6945B73ed554DF8D52ecDf1Ab08F17564386e0f; address public constant IMPISHCRYSTAL = 0x2dC9a47124E15619a07934D14AB497A085C2C918; address public constant SPIRALBITS = 0x650A9960673688Ba924615a2D28c39A8E015fB19; address public constant SPIRALMARKET = 0x75ae378320E1cDe25a496Dfa22972d253Fc2270F; address public constant RWMARKET = 0x47eF85Dfb775aCE0934fBa9EEd09D22e6eC0Cc08; address payable public constant STAKINGV2 = payable(0x2069cB988d5B17Bab70d73076d6F1a9757A4f963); // We will set the pool fee to 1%. uint24 public constant POOL_FEE = 10000; constructor(ISwapRouter _swapRouter) { swapRouter = _swapRouter; // Approve the router to spend the WETH9, MAGIC and SPIRALBITS TransferHelper.safeApprove(WETH9, address(swapRouter), 2**256 - 1); TransferHelper.safeApprove(SPIRALBITS, address(swapRouter), 2**256 - 1); TransferHelper.safeApprove(MAGIC, address(swapRouter), 2**256 - 1); // Approve the NFTs and tokens for this contract as well. IERC721(RWNFT).setApprovalForAll(STAKINGV2, true); IERC721(IMPISHSPIRAL).setApprovalForAll(STAKINGV2, true); IERC721(IMPISHCRYSTAL).setApprovalForAll(STAKINGV2, true); IERC20(SPIRALBITS).approve(STAKINGV2, 2**256 - 1); IERC20(IMPISH).approve(STAKINGV2, 2**256 - 1); // Allow ImpishCrystals to spend our SPIRALBITS (to grow crystals) IERC20(SPIRALBITS).approve(IMPISHCRYSTAL, 2**256 - 1); } function maybeStakeRW(uint256 tokenId, bool stake) internal { if (!stake) { // transfer the NFT to the sender IERC721(RWNFT).safeTransferFrom(address(this), msg.sender, tokenId); } else { uint32[] memory tokens = new uint32[](1); tokens[0] = uint32(tokenId) + 1_000_000; // ContractId for RWNFT is 1,000,000 StakingV2(STAKINGV2).stakeNFTsForOwner(tokens, msg.sender); } } // Buy and Stake a RWNFT function buyAndStakeRW(uint256 tokenId, bool stake) internal { InterfaceImpishDAO(IMPISH).buyNFT(tokenId); maybeStakeRW(tokenId, stake); } function buyRwNFTFromDaoWithEthDirect(uint256 tokenId, bool stake) external payable { uint256 nftPriceInIMPISH = InterfaceImpishDAO(IMPISH).buyNFTPrice(tokenId); // We add 1 wei, because we've divided by 1000, which will remove the smallest 4 digits // and we need to add it back because he actual price has those 4 least significant digits. InterfaceImpishDAO(IMPISH).deposit{value: (nftPriceInIMPISH / 1000) + 1}(); buyAndStakeRW(tokenId, stake); // Return any excess if (address(this).balance > 0) { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "TransferFailed"); } } function buyRwNFTFromDaoWithEth(uint256 tokenId, bool stake) external payable { // Get the buyNFT price uint256 nftPriceInIMPISH = InterfaceImpishDAO(IMPISH).buyNFTPrice(tokenId); swapExactOutputImpishFromEth(nftPriceInIMPISH, msg.value); buyAndStakeRW(tokenId, stake); } function buyRwNFTFromDaoWithSpiralBits( uint256 tokenId, uint256 maxSpiralBits, bool stake ) external { // Get the buyNFT price uint256 nftPriceInIMPISH = InterfaceImpishDAO(IMPISH).buyNFTPrice(tokenId); swapExactOutputImpishFromSpiralBits(nftPriceInIMPISH, maxSpiralBits); buyAndStakeRW(tokenId, stake); } function buySpiralFromMarketWithSpiralBits( uint256 tokenId, uint256 maxSpiralBits, bool stake ) external { // Get the price for this Spiral TokenId (uint256 priceInEth, ) = ISpiralMarket(SPIRALMARKET).forSale(tokenId); // Swap SPIRALBITS -> WETH9 swapExactOutputEthFromSpiralBits(priceInEth, maxSpiralBits); // WETH9 -> ETH IWETH9(WETH9).withdraw(priceInEth); // Buy the Spiral ISpiralMarket(SPIRALMARKET).buySpiral{value: priceInEth}(tokenId); if (!stake) { // transfer the NFT to the sender IERC721(IMPISHSPIRAL).safeTransferFrom(address(this), msg.sender, tokenId); } else { uint32[] memory tokens = new uint32[](1); tokens[0] = uint32(tokenId) + 2_000_000; // ContractId for Spirals is 2,000,000; StakingV2(STAKINGV2).stakeNFTsForOwner(tokens, msg.sender); } } function buyRwNFTFromRWMarket( uint256 offerId, uint256 tokenId, uint256 priceInEth, uint256 maxSpiralBits, bool stake ) external { // Swap SPIRALBITS -> WETH9 swapExactOutputEthFromSpiralBits(priceInEth, maxSpiralBits); // WETH9 -> ETH IWETH9(WETH9).withdraw(IWETH9(WETH9).balanceOf(address(this))); // Buy RW IRWMarket(RWMARKET).acceptSellOffer{value: priceInEth}(offerId); // Stake or Return to msg.sender maybeStakeRW(tokenId, stake); } function multiMintWithMagic(uint8 count, uint96 value) external { magicToEth(uint256(value)); require(count > 0, "AtLeastOne"); require(count <= 10, "AtMost10"); // This function doesn't check if you've sent enough money. If you didn't it will revert // because the mintSpiralRandom will fail uint8 mintedSoFar; uint256 nextTokenId = ImpishSpiral(IMPISHSPIRAL)._tokenIdCounter(); for (mintedSoFar = 0; mintedSoFar < count; mintedSoFar++) { uint256 price = ImpishSpiral(IMPISHSPIRAL).getMintPrice(); ImpishSpiral(IMPISHSPIRAL).mintSpiralRandom{value: price}(); ImpishSpiral(IMPISHSPIRAL).safeTransferFrom(address(this), msg.sender, nextTokenId); nextTokenId += 1; } // If there is any excess money left, send it back if (address(this).balance > 0) { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } } function megaMintWithMagic( address owner, uint32 count, uint256 value ) external { magicToEth(value); megaMint(owner, count); } // A megamint does many things at once: // Mint a RWNFT // Mint a Companion Spiral // Mint a gen0 Crystal // Buy SPIRALBITS on Uniswap // Grow the crystals to max size // Stake all NFTs and IMPISH and SPIRALBITS function megaMint(address owner, uint32 count) public payable { // The TokenId of the first token minted uint256 rwTokenId = IRandomWalkNFT(RWNFT).nextTokenId(); for (uint256 i = 0; i < count; i++) { IRandomWalkNFT(RWNFT).mint{value: IRandomWalkNFT(RWNFT).getMintPrice()}(); } // Spirals uint256 spiralTokenId = ImpishSpiral(IMPISHSPIRAL)._tokenIdCounter(); uint32[] memory spiralTokenIds = new uint32[](count); for (uint256 i = 0; i < count; i++) { spiralTokenIds[i] = uint32(spiralTokenId + i); ImpishSpiral(IMPISHSPIRAL).mintSpiralWithRWNFT{value: ImpishSpiral(IMPISHSPIRAL).getMintPrice()}(rwTokenId + i); } // Crystals uint256 crystalTokenId = ImpishCrystal(IMPISHCRYSTAL)._tokenIdCounter(); ImpishCrystal(IMPISHCRYSTAL).mintCrystals(spiralTokenIds, 0); // Swap all remaining ETH into SPIRALBITS. Note this doesn't refund anything back to the user. swapExactInputSpiralBitsFromEthNoRefund(address(this).balance); // Grow all the crystals to max size for (uint256 i = 0; i < count; i++) { // Newly created crystals are size 30, so we need to grow them 70 more. ImpishCrystal(IMPISHCRYSTAL).grow(uint32(crystalTokenId + i), 70); } // Calculate all the contractTokenIDs, needed for staking uint32[] memory contractTokenIds = new uint32[](count * 3); for (uint256 i = 0; i < count; i++) { contractTokenIds[i * 3 + 0] = uint32(rwTokenId + i + 1_000_000); contractTokenIds[i * 3 + 1] = uint32(spiralTokenId + i + 2_000_000); // Fully grown crystals are contractID 4,000,000 contractTokenIds[i * 3 + 2] = uint32(crystalTokenId + i + 4_000_000); } StakingV2(STAKINGV2).stakeNFTsForOwner(contractTokenIds, owner); // Stake any remaining SPIRALBITS uint256 spiralBitsBalance = IERC20(SPIRALBITS).balanceOf(address(this)); if (spiralBitsBalance > 0) { StakingV2(STAKINGV2).stakeSpiralBitsForOwner(spiralBitsBalance, owner); } // Stake any remaining IMPISH uint256 impishBalance = IERC20(IMPISH).balanceOf(address(this)); if (impishBalance > 0) { StakingV2(STAKINGV2).stakeImpishForOwner(impishBalance, owner); } } /// ------- SWAP Functions function magicToEth(uint256 value) internal { // Transfer MAGIC in TransferHelper.safeTransferFrom(MAGIC, msg.sender, address(this), value); ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: MAGIC, tokenOut: WETH9, fee: POOL_FEE, recipient: address(this), deadline: block.timestamp, amountIn: value, amountOutMinimum: 0, sqrtPriceLimitX96: 0 }); // Executes the swap returning the amountOut that was swapped. uint256 amountOut = swapRouter.exactInputSingle(params); IWETH9(WETH9).withdraw(amountOut); } // function buyMagic_TODO_TEMP() external payable { // // Convert to WETH, since that's what Uniswap uses // uint256 amountIn = address(this).balance; // IWETH9(WETH9).deposit{value: amountIn}(); // ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ // tokenIn: WETH9, // tokenOut: MAGIC, // fee: POOL_FEE, // recipient: address(this), // deadline: block.timestamp, // amountIn: amountIn, // amountOutMinimum: 0, // sqrtPriceLimitX96: 0 // }); // // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. // uint256 amountOut = swapRouter.exactInputSingle(params); // console.log("Swapped to MAGIC", amountOut); // TransferHelper.safeTransfer(MAGIC, msg.sender, amountOut); // } function swapExactInputSpiralBitsFromEthNoRefund(uint256 amountIn) internal returns (uint256 amountOut) { // Convert to WETH, since that's what Uniswap uses IWETH9(WETH9).deposit{value: address(this).balance}(); ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: WETH9, tokenOut: SPIRALBITS, fee: POOL_FEE, recipient: address(this), deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: 0, sqrtPriceLimitX96: 0 }); // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. amountOut = swapRouter.exactInputSingle(params); } /// Swap with Uniswap V3 for the exact amountOut, using upto amountInMaximum of ETH function swapExactOutputEthFromSpiralBits(uint256 amountOut, uint256 amountInMaximum) internal returns (uint256 amountIn) { // Transfer spiralbits in TransferHelper.safeTransferFrom(SPIRALBITS, msg.sender, address(this), amountInMaximum); ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams({ tokenIn: SPIRALBITS, tokenOut: WETH9, fee: POOL_FEE, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum, sqrtPriceLimitX96: 0 }); // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. amountIn = swapRouter.exactOutputSingle(params); // For exact output swaps, the amountInMaximum may not have all been spent. // If the actual amount spent (amountIn) is less than the specified maximum amount, // we must refund the msg.sender if (amountIn < amountInMaximum) { TransferHelper.safeTransfer(SPIRALBITS, msg.sender, amountInMaximum - amountIn); } } /// Swap with Uniswap V3 for the exact amountOut, using upto amountInMaximum of ETH function swapExactOutputImpishFromEth(uint256 amountOut, uint256 amountInMaximum) internal returns (uint256 amountIn) { // Convert to WETH, since that's what Uniswap uses IWETH9(WETH9).deposit{value: address(this).balance}(); ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams({ tokenIn: WETH9, tokenOut: IMPISH, fee: POOL_FEE, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum, sqrtPriceLimitX96: 0 }); // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. amountIn = swapRouter.exactOutputSingle(params); // For exact output swaps, the amountInMaximum may not have all been spent. // If the actual amount spent (amountIn) is less than the specified maximum amount, // we must refund the msg.sender if (amountIn < amountInMaximum) { IWETH9(WETH9).withdraw(IWETH9(WETH9).balanceOf(address(this))); (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "TransferFailed"); } } /// Swap with Uniswap V3 for the exact amountOut, using upto amountInMaximum of SPIRALBITS function swapExactOutputImpishFromSpiralBits(uint256 amountOut, uint256 amountInMaximum) internal returns (uint256 amountIn) { // Transfer spiralbits in TransferHelper.safeTransferFrom(SPIRALBITS, msg.sender, address(this), amountInMaximum); ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({ path: abi.encodePacked(IMPISH, POOL_FEE, WETH9, POOL_FEE, SPIRALBITS), recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum }); // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. amountIn = swapRouter.exactOutput(params); // For exact output swaps, the amountInMaximum may not have all been spent. // If the actual amount spent (amountIn) is less than the specified maximum amount, // we must refund the msg.sender if (amountIn < amountInMaximum) { TransferHelper.safeTransfer(SPIRALBITS, msg.sender, amountInMaximum - amountIn); } } // Default payable function, so the contract can accept any refunds receive() external payable { // Do nothing } // Function that marks this contract can accept incoming NFT transfers function onERC721Received( address, address, uint256, bytes calldata ) public pure returns (bytes4) { // Return this value to accept the NFT return IERC721Receiver.onERC721Received.selector; } }
Get the buyNFT price
function buyRwNFTFromDaoWithSpiralBits( uint256 tokenId, uint256 maxSpiralBits, bool stake ) external { uint256 nftPriceInIMPISH = InterfaceImpishDAO(IMPISH).buyNFTPrice(tokenId); swapExactOutputImpishFromSpiralBits(nftPriceInIMPISH, maxSpiralBits); buyAndStakeRW(tokenId, stake); }
6,447,017
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint a, uint b) internal pure returns (bool, uint) { uint c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint a, uint b) internal pure returns (bool, uint) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint a, uint b) internal pure returns (bool, uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint a, uint b) internal pure returns (bool, uint) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint a, uint b) internal pure returns (bool, uint) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint a, uint b) internal pure returns (uint) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/protocol/IStrategy.sol /* version 1.2.0 Changes Changes listed here do not affect interaction with other contracts (Vault and Controller) - removed function assets(address _token) external view returns (bool); - remove function deposit(uint), declared in IStrategyERC20 - add function setSlippage(uint _slippage); - add function setDelta(uint _delta); */ interface IStrategy { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying asset (ETH or ERC20) @dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy */ function underlying() external view returns (address); /* @notice Returns total amount of underlying transferred from vault */ function totalDebt() external view returns (uint); function performanceFee() external view returns (uint); function slippage() external view returns (uint); /* @notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN */ function delta() external view returns (uint); /* @dev Flag to force exit in case normal exit fails */ function forceExit() external view returns (bool); function setAdmin(address _admin) external; function setController(address _controller) external; function setPerformanceFee(uint _fee) external; function setSlippage(uint _slippage) external; function setDelta(uint _delta) external; function setForceExit(bool _forceExit) external; /* @notice Returns amount of underlying asset locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying asset is invested */ function totalAssets() external view returns (uint); /* @notice Withdraw `_amount` underlying asset @param amount Amount of underlying asset to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying asset from strategy */ function withdrawAll() external; /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external; /* @notice Exit from strategy @dev Must transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer @dev _token must not be equal to underlying token */ function sweep(address _token) external; } // File: contracts/protocol/IStrategyETH.sol interface IStrategyETH is IStrategy { /* @notice Deposit ETH */ function deposit() external payable; } // File: contracts/strategies/StrategyNoOpETH.sol /* version 1.2.0 */ /* This is a "placeholder" strategy used during emergency shutdown */ contract StrategyNoOpETH is IStrategyETH { using SafeERC20 for IERC20; address public override admin; address public override controller; address public override vault; // Placeholder address of ETH, indicating this is strategy for ETH address public constant override underlying = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant override totalDebt = 0; uint public constant override performanceFee = 0; uint public constant override slippage = 0; uint public constant override delta = 0; bool public constant override forceExit = false; constructor(address _controller, address _vault) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); admin = msg.sender; controller = _controller; vault = _vault; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault, "!authorized" ); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } // @dev variable name is removed to silence compiler warning function setPerformanceFee(uint) external override { revert("no-op"); } // @dev variable name is removed to silence compiler warning function setSlippage(uint) external override { revert("no-op"); } // @dev variable name is removed to silence compiler warning function setDelta(uint) external override { revert("no-op"); } // @dev variable name is removed to silence compiler warning function setForceExit(bool) external override { revert("no-op"); } function totalAssets() external view override returns (uint) { return 0; } function deposit() external payable override { revert("no-op"); } // @dev variable name is removed to silence compiler warning function withdraw(uint) external override { revert("no-op"); } // @dev tranfser accidentally sent ETH back to vault function withdrawAll() external override onlyAuthorized { uint bal = address(this).balance; if (bal > 0) { (bool sent, ) = vault.call{value: bal}(""); require(sent, "Send ETH failed"); } } function harvest() external override { revert("no-op"); } function skim() external override { revert("no-op"); } function exit() external override { // this function must not fail for vault to exit this strategy } function sweep(address _token) external override onlyAdmin { IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } }
variable name is removed to silence compiler warning
function setDelta(uint) external override { revert("no-op"); }
1,334,434
/* The MIT License (MIT) Copyright 2017 - 2018, Alchemy Limited, LLC and Smart Contract Solutions. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.21; /** * Reference: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol * * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } /* end SafeMath library */ /// @title Math operation when both numbers has decimal places. /// @notice Use this contract when both numbers has 18 decimal places. contract FixedMath { using SafeMath for uint; uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; uint constant internal DECIMALS = 18; uint constant internal DECMULT = 10 ** DECIMALS; /// @notice Multiplication. function fMul(uint x, uint y) internal pure returns (uint) { return (x.mul(y)).div(DECMULT); } /// @notice Division. function fDiv(uint numerator, uint divisor) internal pure returns (uint) { return (numerator.mul(DECMULT)).div(divisor); } /// @notice Square root. /// @dev Reference: https://stackoverflow.com/questions/3766020/binary-search-to-compute-square-root-java function fSqrt(uint n) internal pure returns (uint) { if (n == 0) { return 0; } uint z = n * n; require(z / n == n); uint high = fAdd(n, DECMULT); uint low = 0; while (fSub(high, low) > 1) { uint mid = fAdd(low, high) / 2; if (fSqr(mid) <= n) { low = mid; } else { high = mid; } } return low; } /// @notice Square. function fSqr(uint n) internal pure returns (uint) { return fMul(n, n); } /// @notice Add. function fAdd(uint x, uint y) internal pure returns (uint) { return x.add(y); } /// @notice Sub. function fSub(uint x, uint y) internal pure returns (uint) { return x.sub(y); } } /// @title A formula contract for converter contract Formula is FixedMath { /// @notice Trade in reserve(ETH/MET) and mint new smart tokens /// @param smartTokenSupply Total supply of smart token /// @param reserveTokensSent Amount of token sent by caller /// @param reserveTokenBalance Balance of reserve token in the contract /// @return Smart token minted function returnForMint(uint smartTokenSupply, uint reserveTokensSent, uint reserveTokenBalance) internal pure returns (uint) { uint s = smartTokenSupply; uint e = reserveTokensSent; uint r = reserveTokenBalance; /// smartToken for mint(T) = S * (sqrt(1 + E/R) - 1) /// DECMULT is same as 1 for values with 18 decimal places return ((fMul(s, (fSub(fSqrt(fAdd(DECMULT, fDiv(e, r))), DECMULT)))).mul(METDECMULT)).div(DECMULT); } /// @notice Redeem smart tokens, get back reserve(ETH/MET) token /// @param smartTokenSupply Total supply of smart token /// @param smartTokensSent Smart token sent /// @param reserveTokenBalance Balance of reserve token in the contract /// @return Reserve token redeemed function returnForRedemption(uint smartTokenSupply, uint smartTokensSent, uint reserveTokenBalance) internal pure returns (uint) { uint s = smartTokenSupply; uint t = smartTokensSent; uint r = reserveTokenBalance; /// reserveToken (E) = R * (1 - (1 - T/S)**2) /// DECMULT is same as 1 for values with 18 decimal places return ((fMul(r, (fSub(DECMULT, fSqr(fSub(DECMULT, fDiv(t, s))))))).mul(METDECMULT)).div(DECMULT); } } /// @title Pricer contract to calculate descending price during auction. contract Pricer { using SafeMath for uint; uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; uint public minimumPrice = 33*10**11; uint public minimumPriceInDailyAuction = 1; uint public tentimes; uint public hundredtimes; uint public thousandtimes; uint constant public MULTIPLIER = 1984320568*10**5; /// @notice Pricer constructor, calculate 10, 100 and 1000 times of 0.99. function initPricer() public { uint x = METDECMULT; uint i; /// Calculate 10 times of 0.99 for (i = 0; i < 10; i++) { x = x.mul(99).div(100); } tentimes = x; x = METDECMULT; /// Calculate 100 times of 0.99 using tentimes calculated above. /// tentimes has 18 decimal places and due to this METDECMLT is /// used as divisor. for (i = 0; i < 10; i++) { x = x.mul(tentimes).div(METDECMULT); } hundredtimes = x; x = METDECMULT; /// Calculate 1000 times of 0.99 using hundredtimes calculated above. /// hundredtimes has 18 decimal places and due to this METDECMULT is /// used as divisor. for (i = 0; i < 10; i++) { x = x.mul(hundredtimes).div(METDECMULT); } thousandtimes = x; } /// @notice Price of MET at nth minute out during operational auction /// @param initialPrice The starting price ie last purchase price /// @param _n The number of minutes passed since last purchase /// @return The resulting price function priceAt(uint initialPrice, uint _n) public view returns (uint price) { uint mult = METDECMULT; uint i; uint n = _n; /// If quotient of n/1000 is greater than 0 then calculate multiplier by /// multiplying thousandtimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/1000. if (n / 1000 > 0) { for (i = 0; i < n / 1000; i++) { mult = mult.mul(thousandtimes).div(METDECMULT); } n = n % 1000; } /// If quotient of n/100 is greater than 0 then calculate multiplier by /// multiplying hundredtimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/100. if (n / 100 > 0) { for (i = 0; i < n / 100; i++) { mult = mult.mul(hundredtimes).div(METDECMULT); } n = n % 100; } /// If quotient of n/10 is greater than 0 then calculate multiplier by /// multiplying tentimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/10. if (n / 10 > 0) { for (i = 0; i < n / 10; i++) { mult = mult.mul(tentimes).div(METDECMULT); } n = n % 10; } /// Calculate multiplier by multiplying 0.99 and mult, repeat it n times. for (i = 0; i < n; i++) { mult = mult.mul(99).div(100); } /// price is calculated as initialPrice multiplied by 0.99 and that too _n times. /// Here mult is METDECMULT multiplied by 0.99 and that too _n times. price = initialPrice.mul(mult).div(METDECMULT); if (price < minimumPriceInDailyAuction) { price = minimumPriceInDailyAuction; } } /// @notice Price of MET at nth minute during initial auction. /// @param lastPurchasePrice The price of MET in last transaction /// @param numTicks The number of minutes passed since last purchase /// @return The resulting price function priceAtInitialAuction(uint lastPurchasePrice, uint numTicks) public view returns (uint price) { /// Price will decrease linearly every minute by the factor of MULTIPLIER. /// If lastPurchasePrice is greater than decrease in price then calculated the price. /// Return minimumPrice, if calculated price is less than minimumPrice. /// If decrease in price is more than lastPurchasePrice then simply return the minimumPrice. if (lastPurchasePrice > MULTIPLIER.mul(numTicks)) { price = lastPurchasePrice.sub(MULTIPLIER.mul(numTicks)); } if (price < minimumPrice) { price = minimumPrice; } } } /// @dev Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md /// @notice ERC20 standard interface interface ERC20 { function totalSupply() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint256); function allowance(address _owner, address _spender) public constant returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function approve(address _spender, uint256 _value) public returns (bool); } /// @title Ownable contract Ownable { address public owner; event OwnershipChanged(address indexed prevOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param _newOwner /// @return true/false function changeOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != address(0)); require(_newOwner != owner); emit OwnershipChanged(owner, _newOwner); owner = _newOwner; return true; } } /// @title Owned contract Owned is Ownable { address public newOwner; /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param _newOwner /// @return true/false function changeOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != owner); newOwner = _newOwner; return true; } /// @notice Allows the new owner to accept ownership of the contract. /// @return true/false function acceptOwnership() public returns (bool) { require(msg.sender == newOwner); emit OwnershipChanged(owner, newOwner); owner = newOwner; return true; } } /// @title Mintable contract to allow minting and destroy. contract Mintable is Owned { using SafeMath for uint256; event Mint(address indexed _to, uint _value); event Destroy(address indexed _from, uint _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); uint256 internal _totalSupply; mapping(address => uint256) internal _balanceOf; address public autonomousConverter; address public minter; ITokenPorter public tokenPorter; /// @notice init reference of other contract and initial supply /// @param _autonomousConverter /// @param _minter /// @param _initialSupply /// @param _decmult Decimal places function initMintable(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { require(autonomousConverter == 0x0 && _autonomousConverter != 0x0); require(minter == 0x0 && _minter != 0x0); autonomousConverter = _autonomousConverter; minter = _minter; _totalSupply = _initialSupply.mul(_decmult); _balanceOf[_autonomousConverter] = _totalSupply; } function totalSupply() public constant returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public constant returns (uint256) { return _balanceOf[_owner]; } /// @notice set address of token porter /// @param _tokenPorter address of token porter function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); tokenPorter = ITokenPorter(_tokenPorter); return true; } /// @notice allow minter and tokenPorter to mint token and assign to address /// @param _to /// @param _value Amount to be minted function mint(address _to, uint _value) public returns (bool) { require(msg.sender == minter || msg.sender == address(tokenPorter)); _balanceOf[_to] = _balanceOf[_to].add(_value); _totalSupply = _totalSupply.add(_value); emit Mint(_to, _value); emit Transfer(0x0, _to, _value); return true; } /// @notice allow autonomousConverter and tokenPorter to mint token and assign to address /// @param _from /// @param _value Amount to be destroyed function destroy(address _from, uint _value) public returns (bool) { require(msg.sender == autonomousConverter || msg.sender == address(tokenPorter)); _balanceOf[_from] = _balanceOf[_from].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Destroy(_from, _value); emit Transfer(_from, 0x0, _value); return true; } } /// @title Token contract contract Token is ERC20, Mintable { mapping(address => mapping(address => uint256)) internal _allowance; function initToken(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { initMintable(_autonomousConverter, _minter, _initialSupply, _decmult); } /// @notice Provide allowance information function allowance(address _owner, address _spender) public constant returns (uint256) { return _allowance[_owner][_spender]; } /// @notice Transfer tokens from sender to the provided address. /// @param _to Receiver of the tokens /// @param _value Amount of token /// @return true/false function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != minter); require(_to != address(this)); require(_to != autonomousConverter); Proceeds proceeds = Auctions(minter).proceeds(); require((_to != address(proceeds))); _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer tokens based on allowance. /// msg.sender must have allowance for spending the tokens from owner ie _from /// @param _from Owner of the tokens /// @param _to Receiver of the tokens /// @param _value Amount of tokens to transfer /// @return true/false function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != minter && _from != minter); require(_to != address(this) && _from != address(this)); Proceeds proceeds = Auctions(minter).proceeds(); require(_to != address(proceeds) && _from != address(proceeds)); //AC can accept MET via this function, needed for MetToEth conversion require(_from != autonomousConverter); require(_allowance[_from][msg.sender] >= _value); _balanceOf[_from] = _balanceOf[_from].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /// @notice Approve spender to spend the tokens ie approve allowance /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(this)); _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @notice Transfer the tokens from sender to all the address provided in the array. /// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. /// @param bits array of uint /// @return true/false function multiTransfer(uint[] bits) public returns (bool) { for (uint i = 0; i < bits.length; i++) { address a = address(bits[i] >> 96); uint amount = bits[i] & ((1 << 96) - 1); if (!transfer(a, amount)) revert(); } return true; } /// @notice Increase allowance of spender /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approveMore(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.add(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } /// @notice Decrease allowance of spender /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approveLess(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.sub(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } } /// @title Smart tokens are an intermediate token generated during conversion of MET-ETH contract SmartToken is Mintable { uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; function initSmartToken(address _autonomousConverter, address _minter, uint _initialSupply) public onlyOwner { initMintable(_autonomousConverter, _minter, _initialSupply, METDECMULT); } } /// @title ERC20 token. Metronome token contract METToken is Token { string public constant name = "Metronome"; string public constant symbol = "MET"; uint8 public constant decimals = 18; bool public transferAllowed; function initMETToken(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { initToken(_autonomousConverter, _minter, _initialSupply, _decmult); } /// @notice Transferable modifier to allow transfer only after initial auction ended. modifier transferable() { require(transferAllowed); _; } function enableMETTransfers() public returns (bool) { require(!transferAllowed && Auctions(minter).isInitialAuctionEnded()); transferAllowed = true; return true; } /// @notice Transfer tokens from caller to another address /// @param _to address The address which you want to transfer to /// @param _value uint256 the amout of tokens to be transfered function transfer(address _to, uint256 _value) public transferable returns (bool) { return super.transfer(_to, _value); } /// @notice Transfer tokens from one address to another /// @param _from address The address from which you want to transfer /// @param _to address The address which you want to transfer to /// @param _value uint256 the amout of tokens to be transfered function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) { return super.transferFrom(_from, _to, _value); } /// @notice Transfer the token from sender to all the addresses provided in array. /// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. /// @param bits array of uint /// @return true/false function multiTransfer(uint[] bits) public transferable returns (bool) { return super.multiTransfer(bits); } mapping (address => bytes32) public roots; function setRoot(bytes32 data) public { roots[msg.sender] = data; } function getRoot(address addr) public view returns (bytes32) { return roots[addr]; } function rootsMatch(address a, address b) public view returns (bool) { return roots[a] == roots[b]; } /// @notice import MET tokens from another chain to this chain. /// @param _destinationChain destination chain name /// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr /// @param _extraData extra information for import /// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash /// @param _supplyOnAllChains MET supply on all supported chains /// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee /// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable /// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime /// @param _proof proof /// @return true/false function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool) { require(address(tokenPorter) != 0x0); return tokenPorter.importMET(_originChain, _destinationChain, _addresses, _extraData, _burnHashes, _supplyOnAllChains, _importData, _proof); } /// @notice export MET tokens from this chain to another chain. /// @param _destChain destination chain address /// @param _destMetronomeAddr address of Metronome contract on the destination chain /// where this MET will be imported. /// @param _destRecipAddr address of account on destination chain /// @param _amount amount /// @param _extraData extra information for future expansion /// @return true/false function export(bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool) { require(address(tokenPorter) != 0x0); return tokenPorter.export(msg.sender, _destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData); } struct Sub { uint startTime; uint payPerWeek; uint lastWithdrawTime; } event LogSubscription(address indexed subscriber, address indexed subscribesTo); event LogCancelSubscription(address indexed subscriber, address indexed subscribesTo); mapping (address => mapping (address => Sub)) public subs; /// @notice subscribe for a weekly recurring payment /// @param _startTime Subscription start time. /// @param _payPerWeek weekly payment /// @param _recipient address of beneficiary /// @return true/false function subscribe(uint _startTime, uint _payPerWeek, address _recipient) public returns (bool) { require(_startTime >= block.timestamp); require(_payPerWeek != 0); require(_recipient != 0); subs[msg.sender][_recipient] = Sub(_startTime, _payPerWeek, _startTime); emit LogSubscription(msg.sender, _recipient); return true; } /// @notice cancel a subcription. /// @param _recipient address of beneficiary /// @return true/false function cancelSubscription(address _recipient) public returns (bool) { require(subs[msg.sender][_recipient].startTime != 0); require(subs[msg.sender][_recipient].payPerWeek != 0); subs[msg.sender][_recipient].startTime = 0; subs[msg.sender][_recipient].payPerWeek = 0; subs[msg.sender][_recipient].lastWithdrawTime = 0; emit LogCancelSubscription(msg.sender, _recipient); return true; } /// @notice get subcription details /// @param _owner /// @param _recipient /// @return startTime, payPerWeek, lastWithdrawTime function getSubscription(address _owner, address _recipient) public constant returns (uint startTime, uint payPerWeek, uint lastWithdrawTime) { Sub storage sub = subs[_owner][_recipient]; return ( sub.startTime, sub.payPerWeek, sub.lastWithdrawTime ); } /// @notice caller can withdraw the token from subscribers. /// @param _owner subcriber /// @return true/false function subWithdraw(address _owner) public transferable returns (bool) { require(subWithdrawFor(_owner, msg.sender)); return true; } /// @notice Allow callers to withdraw token in one go from all of its subscribers /// @param _owners array of address of subscribers /// @return number of successful transfer done function multiSubWithdraw(address[] _owners) public returns (uint) { uint n = 0; for (uint i=0; i < _owners.length; i++) { if (subWithdrawFor(_owners[i], msg.sender)) { n++; } } return n; } /// @notice Trigger MET token transfers for all pairs of subscribers and beneficiaries /// @dev address at i index in owners and recipients array is subcriber-beneficiary pair. /// @param _owners /// @param _recipients /// @return number of successful transfer done function multiSubWithdrawFor(address[] _owners, address[] _recipients) public returns (uint) { // owners and recipients need 1-to-1 mapping, must be same length require(_owners.length == _recipients.length); uint n = 0; for (uint i = 0; i < _owners.length; i++) { if (subWithdrawFor(_owners[i], _recipients[i])) { n++; } } return n; } function subWithdrawFor(address _from, address _to) internal returns (bool) { Sub storage sub = subs[_from][_to]; if (sub.startTime > 0 && sub.startTime < block.timestamp && sub.payPerWeek > 0) { uint weekElapsed = (now.sub(sub.lastWithdrawTime)).div(7 days); uint amount = weekElapsed.mul(sub.payPerWeek); if (weekElapsed > 0 && _balanceOf[_from] >= amount) { subs[_from][_to].lastWithdrawTime = block.timestamp; _balanceOf[_from] = _balanceOf[_from].sub(amount); _balanceOf[_to] = _balanceOf[_to].add(amount); emit Transfer(_from, _to, amount); return true; } } return false; } } /// @title Autonomous Converter contract for MET <=> ETH exchange contract AutonomousConverter is Formula, Owned { SmartToken public smartToken; METToken public reserveToken; Auctions public auctions; enum WhichToken { Eth, Met } bool internal initialized = false; event LogFundsIn(address indexed from, uint value); event ConvertEthToMet(address indexed from, uint eth, uint met); event ConvertMetToEth(address indexed from, uint eth, uint met); function init(address _reserveToken, address _smartToken, address _auctions) public onlyOwner payable { require(!initialized); auctions = Auctions(_auctions); reserveToken = METToken(_reserveToken); smartToken = SmartToken(_smartToken); initialized = true; } function handleFund() public payable { require(msg.sender == address(auctions.proceeds())); emit LogFundsIn(msg.sender, msg.value); } function getMetBalance() public view returns (uint) { return balanceOf(WhichToken.Met); } function getEthBalance() public view returns (uint) { return balanceOf(WhichToken.Eth); } /// @notice return the expected MET for ETH /// @param _depositAmount ETH. /// @return expected MET value for ETH function getMetForEthResult(uint _depositAmount) public view returns (uint256) { return convertingReturn(WhichToken.Eth, _depositAmount); } /// @notice return the expected ETH for MET /// @param _depositAmount MET. /// @return expected ETH value for MET function getEthForMetResult(uint _depositAmount) public view returns (uint256) { return convertingReturn(WhichToken.Met, _depositAmount); } /// @notice send ETH and get MET /// @param _mintReturn execute conversion only if return is equal or more than _mintReturn /// @return returnedMet MET retured after conversion function convertEthToMet(uint _mintReturn) public payable returns (uint returnedMet) { returnedMet = convert(WhichToken.Eth, _mintReturn, msg.value); emit ConvertEthToMet(msg.sender, msg.value, returnedMet); } /// @notice send MET and get ETH /// @dev Caller will be required to approve the AutonomousConverter to initiate the transfer /// @param _amount MET amount /// @param _mintReturn execute conversion only if return is equal or more than _mintReturn /// @return returnedEth ETh returned after conversion function convertMetToEth(uint _amount, uint _mintReturn) public returns (uint returnedEth) { returnedEth = convert(WhichToken.Met, _mintReturn, _amount); emit ConvertMetToEth(msg.sender, returnedEth, _amount); } function balanceOf(WhichToken which) internal view returns (uint) { if (which == WhichToken.Eth) return address(this).balance; if (which == WhichToken.Met) return reserveToken.balanceOf(this); revert(); } function convertingReturn(WhichToken whichFrom, uint _depositAmount) internal view returns (uint256) { WhichToken to = WhichToken.Met; if (whichFrom == WhichToken.Met) { to = WhichToken.Eth; } uint reserveTokenBalanceFrom = balanceOf(whichFrom).add(_depositAmount); uint mintRet = returnForMint(smartToken.totalSupply(), _depositAmount, reserveTokenBalanceFrom); uint newSmartTokenSupply = smartToken.totalSupply().add(mintRet); uint reserveTokenBalanceTo = balanceOf(to); return returnForRedemption( newSmartTokenSupply, mintRet, reserveTokenBalanceTo); } function convert(WhichToken whichFrom, uint _minReturn, uint amnt) internal returns (uint) { WhichToken to = WhichToken.Met; if (whichFrom == WhichToken.Met) { to = WhichToken.Eth; require(reserveToken.transferFrom(msg.sender, this, amnt)); } uint mintRet = mint(whichFrom, amnt, 1); return redeem(to, mintRet, _minReturn); } function mint(WhichToken which, uint _depositAmount, uint _minReturn) internal returns (uint256 amount) { require(_minReturn > 0); amount = mintingReturn(which, _depositAmount); require(amount >= _minReturn); require(smartToken.mint(msg.sender, amount)); } function mintingReturn(WhichToken which, uint _depositAmount) internal view returns (uint256) { uint256 smartTokenSupply = smartToken.totalSupply(); uint256 reserveBalance = balanceOf(which); return returnForMint(smartTokenSupply, _depositAmount, reserveBalance); } function redeem(WhichToken which, uint _amount, uint _minReturn) internal returns (uint redeemable) { require(_amount <= smartToken.balanceOf(msg.sender)); require(_minReturn > 0); redeemable = redemptionReturn(which, _amount); require(redeemable >= _minReturn); uint256 reserveBalance = balanceOf(which); require(reserveBalance >= redeemable); uint256 tokenSupply = smartToken.totalSupply(); require(_amount < tokenSupply); smartToken.destroy(msg.sender, _amount); if (which == WhichToken.Eth) { msg.sender.transfer(redeemable); } else { require(reserveToken.transfer(msg.sender, redeemable)); } } function redemptionReturn(WhichToken which, uint smartTokensSent) internal view returns (uint256) { uint smartTokenSupply = smartToken.totalSupply(); uint reserveTokenBalance = balanceOf(which); return returnForRedemption( smartTokenSupply, smartTokensSent, reserveTokenBalance); } } /// @title Proceeds contract contract Proceeds is Owned { using SafeMath for uint256; AutonomousConverter public autonomousConverter; Auctions public auctions; event LogProceedsIn(address indexed from, uint value); event LogClosedAuction(address indexed from, uint value); uint latestAuctionClosed; function initProceeds(address _autonomousConverter, address _auctions) public onlyOwner { require(address(auctions) == 0x0 && _auctions != 0x0); require(address(autonomousConverter) == 0x0 && _autonomousConverter != 0x0); autonomousConverter = AutonomousConverter(_autonomousConverter); auctions = Auctions(_auctions); } function handleFund() public payable { require(msg.sender == address(auctions)); emit LogProceedsIn(msg.sender, msg.value); } /// @notice Forward 0.25% of total ETH balance of proceeds to AutonomousConverter contract function closeAuction() public { uint lastPurchaseTick = auctions.lastPurchaseTick(); uint currentAuction = auctions.currentAuction(); uint val = ((address(this).balance).mul(25)).div(10000); if (val > 0 && (currentAuction > auctions.whichAuction(lastPurchaseTick)) && (latestAuctionClosed < currentAuction)) { latestAuctionClosed = currentAuction; autonomousConverter.handleFund.value(val)(); emit LogClosedAuction(msg.sender, val); } } } /// @title Auction contract. Send ETH to the contract address and buy MET. contract Auctions is Pricer, Owned { using SafeMath for uint256; METToken public token; Proceeds public proceeds; address[] public founders; mapping(address => TokenLocker) public tokenLockers; uint internal constant DAY_IN_SECONDS = 86400; uint internal constant DAY_IN_MINUTES = 1440; uint public genesisTime; uint public lastPurchaseTick; uint public lastPurchasePrice; uint public constant INITIAL_GLOBAL_DAILY_SUPPLY = 2880 * METDECMULT; uint public INITIAL_FOUNDER_SUPPLY = 1999999 * METDECMULT; uint public INITIAL_AC_SUPPLY = 1 * METDECMULT; uint public totalMigratedOut = 0; uint public totalMigratedIn = 0; uint public timeScale = 1; uint public constant INITIAL_SUPPLY = 10000000 * METDECMULT; uint public mintable = INITIAL_SUPPLY; uint public initialAuctionDuration = 7 days; uint public initialAuctionEndTime; uint public dailyAuctionStartTime; uint public constant DAILY_PURCHASE_LIMIT = 1000 ether; mapping (address => uint) internal purchaseInTheAuction; mapping (address => uint) internal lastPurchaseAuction; bool public minted; bool public initialized; uint public globalSupplyAfterPercentageLogic = 52598080 * METDECMULT; uint public constant AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS = 14791; bytes8 public chain = "ETH"; event LogAuctionFundsIn(address indexed sender, uint amount, uint tokens, uint purchasePrice, uint refund); function Auctions() public { mintable = INITIAL_SUPPLY - 2000000 * METDECMULT; } /// @notice Payable function to buy MET in descending price auction function () public payable running { require(msg.value > 0); uint amountForPurchase = msg.value; uint excessAmount; if (currentAuction() > whichAuction(lastPurchaseTick)) { proceeds.closeAuction(); restartAuction(); } if (isInitialAuctionEnded()) { require(now >= dailyAuctionStartTime); if (lastPurchaseAuction[msg.sender] < currentAuction()) { if (amountForPurchase > DAILY_PURCHASE_LIMIT) { excessAmount = amountForPurchase.sub(DAILY_PURCHASE_LIMIT); amountForPurchase = DAILY_PURCHASE_LIMIT; } purchaseInTheAuction[msg.sender] = msg.value; lastPurchaseAuction[msg.sender] = currentAuction(); } else { require(purchaseInTheAuction[msg.sender] < DAILY_PURCHASE_LIMIT); if (purchaseInTheAuction[msg.sender].add(amountForPurchase) > DAILY_PURCHASE_LIMIT) { excessAmount = (purchaseInTheAuction[msg.sender].add(amountForPurchase)).sub(DAILY_PURCHASE_LIMIT); amountForPurchase = amountForPurchase.sub(excessAmount); } purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].add(msg.value); } } uint _currentTick = currentTick(); uint weiPerToken; uint tokens; uint refund; (weiPerToken, tokens, refund) = calcPurchase(amountForPurchase, _currentTick); require(tokens > 0); if (now < initialAuctionEndTime && (token.totalSupply()).add(tokens) >= INITIAL_SUPPLY) { initialAuctionEndTime = now; dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = _currentTick; lastPurchasePrice = weiPerToken; assert(tokens <= mintable); mintable = mintable.sub(tokens); assert(refund <= amountForPurchase); uint ethForProceeds = amountForPurchase.sub(refund); proceeds.handleFund.value(ethForProceeds)(); require(token.mint(msg.sender, tokens)); refund = refund.add(excessAmount); if (refund > 0) { if (purchaseInTheAuction[msg.sender] > 0) { purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].sub(refund); } msg.sender.transfer(refund); } emit LogAuctionFundsIn(msg.sender, ethForProceeds, tokens, lastPurchasePrice, refund); } modifier running() { require(isRunning()); _; } function isRunning() public constant returns (bool) { return (block.timestamp >= genesisTime && genesisTime > 0); } /// @notice current tick(minute) of the metronome clock /// @return tick count function currentTick() public view returns(uint) { return whichTick(block.timestamp); } /// @notice current auction /// @return auction count function currentAuction() public view returns(uint) { return whichAuction(currentTick()); } /// @notice tick count at the timestamp t. /// @param t timestamp /// @return tick count function whichTick(uint t) public view returns(uint) { if (genesisTime > t) { revert(); } return (t - genesisTime) * timeScale / 1 minutes; } /// @notice Auction count at given the timestamp t /// @param t timestamp /// @return Auction count function whichAuction(uint t) public view returns(uint) { if (whichTick(dailyAuctionStartTime) > t) { return 0; } else { return ((t - whichTick(dailyAuctionStartTime)) / DAY_IN_MINUTES) + 1; } } /// @notice one single function telling everything about Metronome Auction function heartbeat() public view returns ( bytes8 _chain, address auctionAddr, address convertAddr, address tokenAddr, uint minting, uint totalMET, uint proceedsBal, uint currTick, uint currAuction, uint nextAuctionGMT, uint genesisGMT, uint currentAuctionPrice, uint _dailyMintable, uint _lastPurchasePrice) { _chain = chain; convertAddr = proceeds.autonomousConverter(); tokenAddr = token; auctionAddr = this; totalMET = token.totalSupply(); proceedsBal = address(proceeds).balance; currTick = currentTick(); currAuction = currentAuction(); if (currAuction == 0) { nextAuctionGMT = dailyAuctionStartTime; } else { nextAuctionGMT = (currAuction * DAY_IN_SECONDS) / timeScale + dailyAuctionStartTime; } genesisGMT = genesisTime; currentAuctionPrice = currentPrice(); _dailyMintable = dailyMintable(); minting = currentMintable(); _lastPurchasePrice = lastPurchasePrice; } /// @notice Skip Initialization and minting if we're not the OG Metronome /// @param _token MET token contract address /// @param _proceeds Address of Proceeds contract /// @param _genesisTime The block.timestamp when first auction started on OG chain /// @param _minimumPrice Nobody can buy tokens for less than this price /// @param _startingPrice Start price of MET when first auction starts /// @param _timeScale time scale factor for auction. will be always 1 in live environment /// @param _chain chain where this contract is being deployed /// @param _initialAuctionEndTime Initial Auction end time in ETH chain. function skipInitBecauseIAmNotOg(address _token, address _proceeds, uint _genesisTime, uint _minimumPrice, uint _startingPrice, uint _timeScale, bytes8 _chain, uint _initialAuctionEndTime) public onlyOwner returns (bool) { require(!minted); require(!initialized); require(_timeScale != 0); require(address(token) == 0x0 && _token != 0x0); require(address(proceeds) == 0x0 && _proceeds != 0x0); initPricer(); // minting substitute section token = METToken(_token); proceeds = Proceeds(_proceeds); INITIAL_FOUNDER_SUPPLY = 0; INITIAL_AC_SUPPLY = 0; mintable = 0; // // initial auction substitute section genesisTime = _genesisTime; initialAuctionEndTime = _initialAuctionEndTime; // if initialAuctionEndTime is midnight, then daily auction will start immediately // after initial auction. if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) { dailyAuctionStartTime = initialAuctionEndTime; } else { dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = 0; if (_minimumPrice > 0) { minimumPrice = _minimumPrice; } timeScale = _timeScale; if (_startingPrice > 0) { lastPurchasePrice = _startingPrice * 1 ether; } else { lastPurchasePrice = 2 ether; } chain = _chain; minted = true; initialized = true; return true; } /// @notice Initialize Auctions parameters /// @param _startTime The block.timestamp when first auction starts /// @param _minimumPrice Nobody can buy tokens for less than this price /// @param _startingPrice Start price of MET when first auction starts /// @param _timeScale time scale factor for auction. will be always 1 in live environment function initAuctions(uint _startTime, uint _minimumPrice, uint _startingPrice, uint _timeScale) public onlyOwner returns (bool) { require(minted); require(!initialized); require(_timeScale != 0); initPricer(); if (_startTime > 0) { genesisTime = (_startTime / (1 minutes)) * (1 minutes) + 60; } else { genesisTime = block.timestamp + 60 - (block.timestamp % 60); } initialAuctionEndTime = genesisTime + initialAuctionDuration; // if initialAuctionEndTime is midnight, then daily auction will start immediately // after initial auction. if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) { dailyAuctionStartTime = initialAuctionEndTime; } else { dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = 0; if (_minimumPrice > 0) { minimumPrice = _minimumPrice; } timeScale = _timeScale; if (_startingPrice > 0) { lastPurchasePrice = _startingPrice * 1 ether; } else { lastPurchasePrice = 2 ether; } for (uint i = 0; i < founders.length; i++) { TokenLocker tokenLocker = tokenLockers[founders[i]]; tokenLocker.lockTokenLocker(); } initialized = true; return true; } function createTokenLocker(address _founder, address _token) public onlyOwner { require(_token != 0x0); require(_founder != 0x0); founders.push(_founder); TokenLocker tokenLocker = new TokenLocker(address(this), _token); tokenLockers[_founder] = tokenLocker; tokenLocker.changeOwnership(_founder); } /// @notice Mint initial supply for founder and move to token locker /// @param _founders Left 160 bits are the founder address and the right 96 bits are the token amount. /// @param _token MET token contract address /// @param _proceeds Address of Proceeds contract function mintInitialSupply(uint[] _founders, address _token, address _proceeds, address _autonomousConverter) public onlyOwner returns (bool) { require(!minted); require(_founders.length != 0); require(address(token) == 0x0 && _token != 0x0); require(address(proceeds) == 0x0 && _proceeds != 0x0); require(_autonomousConverter != 0x0); token = METToken(_token); proceeds = Proceeds(_proceeds); // _founders will be minted into individual token lockers uint foundersTotal; for (uint i = 0; i < _founders.length; i++) { address addr = address(_founders[i] >> 96); require(addr != 0x0); uint amount = _founders[i] & ((1 << 96) - 1); require(amount > 0); TokenLocker tokenLocker = tokenLockers[addr]; require(token.mint(address(tokenLocker), amount)); tokenLocker.deposit(addr, amount); foundersTotal = foundersTotal.add(amount); } // reconcile minted total for founders require(foundersTotal == INITIAL_FOUNDER_SUPPLY); // mint a small amount to the AC require(token.mint(_autonomousConverter, INITIAL_AC_SUPPLY)); minted = true; return true; } /// @notice Suspend auction if not started yet function stopEverything() public onlyOwner { if (genesisTime < block.timestamp) { revert(); } genesisTime = genesisTime + 1000 years; initialAuctionEndTime = genesisTime; dailyAuctionStartTime = genesisTime; } /// @notice Return information about initial auction status. function isInitialAuctionEnded() public view returns (bool) { return (initialAuctionEndTime != 0 && (now >= initialAuctionEndTime || token.totalSupply() >= INITIAL_SUPPLY)); } /// @notice Global MET supply function globalMetSupply() public view returns (uint) { uint currAuc = currentAuction(); if (currAuc > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { return globalSupplyAfterPercentageLogic; } else { return INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(currAuc)); } } /// @notice Global MET daily supply. Daily supply is greater of 1) 2880 2)2% of then outstanding supply per year. /// @dev 2% logic will kicks in at 14792th auction. function globalDailySupply() public view returns (uint) { uint dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY; uint thisAuction = currentAuction(); if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { uint lastAuctionPurchase = whichAuction(lastPurchaseTick); uint recentAuction = AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS + 1; if (lastAuctionPurchase > recentAuction) { recentAuction = lastAuctionPurchase; } uint totalAuctions = thisAuction - recentAuction; if (totalAuctions > 1) { // derived formula to find close to accurate daily supply when some auction missed. uint factor = 36525 + ((totalAuctions - 1) * 2); dailySupply = (globalSupplyAfterPercentageLogic.mul(2).mul(factor)).div(36525 ** 2); } else { dailySupply = globalSupplyAfterPercentageLogic.mul(2).div(36525); } if (dailySupply < INITIAL_GLOBAL_DAILY_SUPPLY) { dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY; } } return dailySupply; } /// @notice Current price of MET in current auction /// @return weiPerToken function currentPrice() public constant returns (uint weiPerToken) { weiPerToken = calcPriceAt(currentTick()); } /// @notice Daily mintable MET in current auction function dailyMintable() public constant returns (uint) { return nextAuctionSupply(0); } /// @notice Total tokens on this chain function tokensOnThisChain() public view returns (uint) { uint totalSupply = token.totalSupply(); uint currMintable = currentMintable(); return totalSupply.add(currMintable); } /// @notice Current mintable MET in auction function currentMintable() public view returns (uint) { uint currMintable = mintable; uint currAuction = currentAuction(); uint totalAuctions = currAuction.sub(whichAuction(lastPurchaseTick)); if (totalAuctions > 0) { currMintable = mintable.add(nextAuctionSupply(totalAuctions)); } return currMintable; } /// @notice prepare auction when first import is done on a non ETH chain function prepareAuctionForNonOGChain() public { require(msg.sender == address(token.tokenPorter()) || msg.sender == address(token)); require(token.totalSupply() == 0); require(chain != "ETH"); lastPurchaseTick = currentTick(); } /// @notice Find out what the results would be of a prospective purchase /// @param _wei Amount of wei the purchaser will pay /// @param _timestamp Prospective purchase timestamp /// @return weiPerToken expected MET token rate /// @return tokens Expected token for a prospective purchase /// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less function whatWouldPurchaseDo(uint _wei, uint _timestamp) public constant returns (uint weiPerToken, uint tokens, uint refund) { weiPerToken = calcPriceAt(whichTick(_timestamp)); uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint weiPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(weiPaying); } } /// @notice Return the information about the next auction /// @return _startTime Start time of next auction /// @return _startPrice Start price of MET in next auction /// @return _auctionTokens MET supply in next auction function nextAuction() internal constant returns(uint _startTime, uint _startPrice, uint _auctionTokens) { if (block.timestamp < genesisTime) { _startTime = genesisTime; _startPrice = lastPurchasePrice; _auctionTokens = mintable; return; } uint recentAuction = whichAuction(lastPurchaseTick); uint currAuc = currentAuction(); uint totalAuctions = currAuc - recentAuction; _startTime = dailyAuctionStartTime; if (currAuc > 1) { _startTime = auctionStartTime(currentTick()); } _auctionTokens = nextAuctionSupply(totalAuctions); if (totalAuctions > 1) { _startPrice = lastPurchasePrice / 100 + 1; } else { if (mintable == 0 || totalAuctions == 0) { // Sold out scenario or someone querying projected start price of next auction _startPrice = (lastPurchasePrice * 2) + 1; } else { // Timed out and all tokens not sold. if (currAuc == 1) { // If initial auction timed out then price before start of new auction will touch floor price _startPrice = minimumPrice * 2; } else { // Descending price till end of auction and then multiply by 2 uint tickWhenAuctionEnded = whichTick(_startTime); uint numTick = 0; if (tickWhenAuctionEnded > lastPurchaseTick) { numTick = tickWhenAuctionEnded - lastPurchaseTick; } _startPrice = priceAt(lastPurchasePrice, numTick) * 2; } } } } /// @notice Calculate results of a purchase /// @param _wei Amount of wei the purchaser will pay /// @param _t Prospective purchase tick /// @return weiPerToken expected MET token rate /// @return tokens Expected token for a prospective purchase /// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less function calcPurchase(uint _wei, uint _t) internal view returns (uint weiPerToken, uint tokens, uint refund) { require(_t >= lastPurchaseTick); uint numTicks = _t - lastPurchaseTick; if (isInitialAuctionEnded()) { weiPerToken = priceAt(lastPurchasePrice, numTicks); } else { weiPerToken = priceAtInitialAuction(lastPurchasePrice, numTicks); } uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint ethPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(ethPaying); } } /// @notice MET supply for next Auction also considering carry forward met. /// @param totalAuctionMissed auction count when no purchase done. function nextAuctionSupply(uint totalAuctionMissed) internal view returns (uint supply) { uint thisAuction = currentAuction(); uint tokensHere = token.totalSupply().add(mintable); supply = INITIAL_GLOBAL_DAILY_SUPPLY; uint dailySupplyAtLastPurchase; if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { supply = globalDailySupply(); if (totalAuctionMissed > 1) { dailySupplyAtLastPurchase = globalSupplyAfterPercentageLogic.mul(2).div(36525); supply = dailySupplyAtLastPurchase.add(supply).mul(totalAuctionMissed).div(2); } supply = (supply.mul(tokensHere)).div(globalSupplyAfterPercentageLogic); } else { if (totalAuctionMissed > 1) { supply = supply.mul(totalAuctionMissed); } uint previousGlobalMetSupply = INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(whichAuction(lastPurchaseTick))); supply = (supply.mul(tokensHere)).div(previousGlobalMetSupply); } } /// @notice price at a number of minutes out in Initial auction and daily auction /// @param _tick Metronome tick /// @return weiPerToken function calcPriceAt(uint _tick) internal constant returns (uint weiPerToken) { uint recentAuction = whichAuction(lastPurchaseTick); uint totalAuctions = whichAuction(_tick).sub(recentAuction); uint prevPrice; uint numTicks = 0; // Auction is sold out and metronome clock is in same auction if (mintable == 0 && totalAuctions == 0) { return lastPurchasePrice; } // Metronome has missed one auction ie no purchase in last auction if (totalAuctions > 1) { prevPrice = lastPurchasePrice / 100 + 1; numTicks = numTicksSinceAuctionStart(_tick); } else if (totalAuctions == 1) { // Metronome clock is in new auction, next auction // previous auction sold out if (mintable == 0) { prevPrice = lastPurchasePrice * 2; } else { // previous auctions timed out // first daily auction if (whichAuction(_tick) == 1) { prevPrice = minimumPrice * 2; } else { prevPrice = priceAt(lastPurchasePrice, numTicksTillAuctionStart(_tick)) * 2; } } numTicks = numTicksSinceAuctionStart(_tick); } else { //Auction is running prevPrice = lastPurchasePrice; numTicks = _tick - lastPurchaseTick; } require(numTicks >= 0); if (isInitialAuctionEnded()) { weiPerToken = priceAt(prevPrice, numTicks); } else { weiPerToken = priceAtInitialAuction(prevPrice, numTicks); } } /// @notice Calculate number of ticks elapsed between auction start time and given tick. /// @param _tick Given metronome tick function numTicksSinceAuctionStart(uint _tick) private view returns (uint ) { uint currentAuctionStartTime = auctionStartTime(_tick); return _tick - whichTick(currentAuctionStartTime); } /// @notice Calculate number of ticks elapsed between lastPurchaseTick and auctions start time of given tick. /// @param _tick Given metronome tick function numTicksTillAuctionStart(uint _tick) private view returns (uint) { uint currentAuctionStartTime = auctionStartTime(_tick); return whichTick(currentAuctionStartTime) - lastPurchaseTick; } /// @notice First calculate the auction which contains the given tick and then calculate /// auction start time of given tick. /// @param _tick Metronome tick function auctionStartTime(uint _tick) private view returns (uint) { return ((whichAuction(_tick)) * 1 days) / timeScale + dailyAuctionStartTime - 1 days; } /// @notice start the next day's auction function restartAuction() private { uint time; uint price; uint auctionTokens; (time, price, auctionTokens) = nextAuction(); uint thisAuction = currentAuction(); if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { globalSupplyAfterPercentageLogic = globalSupplyAfterPercentageLogic.add(globalDailySupply()); } mintable = mintable.add(auctionTokens); lastPurchasePrice = price; lastPurchaseTick = whichTick(time); } } /// @title This contract serves as a locker for a founder's tokens contract TokenLocker is Ownable { using SafeMath for uint; uint internal constant QUARTER = 91 days + 450 minutes; Auctions public auctions; METToken public token; bool public locked = false; uint public deposited; uint public lastWithdrawTime; uint public quarterlyWithdrawable; event Withdrawn(address indexed who, uint amount); event Deposited(address indexed who, uint amount); modifier onlyAuction() { require(msg.sender == address(auctions)); _; } modifier preLock() { require(!locked); _; } modifier postLock() { require(locked); _; } /// @notice Constructor to initialize TokenLocker contract. /// @param _auctions Address of auctions contract /// @param _token Address of METToken contract function TokenLocker(address _auctions, address _token) public { require(_auctions != 0x0); require(_token != 0x0); auctions = Auctions(_auctions); token = METToken(_token); } /// @notice If auctions is initialized, call to this function will result in /// locking of deposited tokens and further deposit of tokens will not be allowed. function lockTokenLocker() public onlyAuction { require(auctions.initialAuctionEndTime() != 0); require(auctions.initialAuctionEndTime() >= auctions.genesisTime()); locked = true; } /// @notice It will deposit tokens into the locker for given beneficiary. /// @param beneficiary Address of the beneficiary, whose tokens are being locked. /// @param amount Amount of tokens being locked function deposit (address beneficiary, uint amount ) public onlyAuction preLock { uint totalBalance = token.balanceOf(this); require(totalBalance.sub(deposited) >= amount); deposited = deposited.add(amount); emit Deposited(beneficiary, amount); } /// @notice This function will allow token withdraw from locker. /// 25% of total deposited tokens can be withdrawn after initial auction end. /// Remaining 75% can be withdrawn in equal amount over 12 quarters. function withdraw() public onlyOwner postLock { require(deposited > 0); uint withdrawable = 0; uint withdrawTime = auctions.initialAuctionEndTime(); if (lastWithdrawTime == 0 && auctions.isInitialAuctionEnded()) { withdrawable = withdrawable.add((deposited.mul(25)).div(100)); quarterlyWithdrawable = (deposited.sub(withdrawable)).div(12); lastWithdrawTime = withdrawTime; } require(lastWithdrawTime != 0); if (now >= lastWithdrawTime.add(QUARTER)) { uint daysSinceLastWithdraw = now.sub(lastWithdrawTime); uint totalQuarters = daysSinceLastWithdraw.div(QUARTER); require(totalQuarters > 0); withdrawable = withdrawable.add(quarterlyWithdrawable.mul(totalQuarters)); if (now >= withdrawTime.add(QUARTER.mul(12))) { withdrawable = deposited; } lastWithdrawTime = lastWithdrawTime.add(totalQuarters.mul(QUARTER)); } if (withdrawable > 0) { deposited = deposited.sub(withdrawable); token.transfer(msg.sender, withdrawable); emit Withdrawn(msg.sender, withdrawable); } } } /// @title Interface for TokenPorter contract. /// Define events and functions for TokenPorter contract interface ITokenPorter { event ExportOnChainClaimedReceiptLog(address indexed destinationMetronomeAddr, address indexed destinationRecipientAddr, uint amount); event ExportReceiptLog(bytes8 destinationChain, address destinationMetronomeAddr, address indexed destinationRecipientAddr, uint amountToBurn, uint fee, bytes extraData, uint currentTick, uint indexed burnSequence, bytes32 indexed currentBurnHash, bytes32 prevBurnHash, uint dailyMintable, uint[] supplyOnAllChains, uint genesisTime, uint blockTimestamp, uint dailyAuctionStartTime); event ImportReceiptLog(address indexed destinationRecipientAddr, uint amountImported, uint fee, bytes extraData, uint currentTick, uint indexed importSequence, bytes32 indexed currentHash, bytes32 prevHash, uint dailyMintable, uint blockTimestamp, address caller); function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool); function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool); } /// @title This contract will provide export functionality for tokens. contract TokenPorter is ITokenPorter, Owned { using SafeMath for uint; Auctions public auctions; METToken public token; Validator public validator; ChainLedger public chainLedger; uint public burnSequence = 1; uint public importSequence = 1; bytes32[] public exportedBurns; uint[] public supplyOnAllChains = new uint[](6); /// @notice mapping that tracks valid destination chains for export mapping(bytes8 => address) public destinationChains; /// @notice Initialize TokenPorter contract. /// @param _tokenAddr Address of metToken contract /// @param _auctionsAddr Address of auctions contract function initTokenPorter(address _tokenAddr, address _auctionsAddr) public onlyOwner { require(_tokenAddr != 0x0); require(_auctionsAddr != 0x0); auctions = Auctions(_auctionsAddr); token = METToken(_tokenAddr); } /// @notice set address of validator contract /// @param _validator address of validator contract function setValidator(address _validator) public onlyOwner returns (bool) { require(_validator != 0x0); validator = Validator(_validator); return true; } /// @notice set address of chainLedger contract /// @param _chainLedger address of chainLedger contract function setChainLedger(address _chainLedger) public onlyOwner returns (bool) { require(_chainLedger != 0x0); chainLedger = ChainLedger(_chainLedger); return true; } /// @notice only owner can add destination chains /// @param _chainName string of destination blockchain name /// @param _contractAddress address of destination MET token to import to function addDestinationChain(bytes8 _chainName, address _contractAddress) public onlyOwner returns (bool) { require(_chainName != 0 && _contractAddress != address(0)); destinationChains[_chainName] = _contractAddress; return true; } /// @notice only owner can remove destination chains /// @param _chainName string of destination blockchain name function removeDestinationChain(bytes8 _chainName) public onlyOwner returns (bool) { require(_chainName != 0); require(destinationChains[_chainName] != address(0)); destinationChains[_chainName] = address(0); return true; } /// @notice holds claims from users that have exported on-chain /// @param key is address of destination MET token contract /// @param subKey is address of users account that burned their original MET token mapping (address => mapping(address => uint)) public claimables; /// @notice destination MET token contract calls claimReceivables to record burned /// tokens have been minted in new chain /// @param recipients array of addresses of each user that has exported from /// original chain. These can be generated by ExportReceiptLog function claimReceivables(address[] recipients) public returns (uint) { require(recipients.length > 0); uint total; for (uint i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint amountBurned = claimables[msg.sender][recipient]; if (amountBurned > 0) { claimables[msg.sender][recipient] = 0; emit ExportOnChainClaimedReceiptLog(msg.sender, recipient, amountBurned); total = total.add(1); } } return total; } /// @notice import MET tokens from another chain to this chain. /// @param _destinationChain destination chain name /// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr /// @param _extraData extra information for import /// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash /// @param _supplyOnAllChains MET supply on all supported chains /// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee /// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable /// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime /// @param _proof proof /// @return true/false function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool) { require(msg.sender == address(token)); require(_importData.length == 8); require(_addresses.length == 2); require(_burnHashes.length == 2); require(validator.isReceiptClaimable(_originChain, _destinationChain, _addresses, _extraData, _burnHashes, _supplyOnAllChains, _importData, _proof)); validator.claimHash(_burnHashes[1]); require(_destinationChain == auctions.chain()); uint amountToImport = _importData[1].add(_importData[2]); require(amountToImport.add(token.totalSupply()) <= auctions.globalMetSupply()); require(_addresses[0] == address(token)); if (_importData[1] == 0) { return false; } if (importSequence == 1 && token.totalSupply() == 0) { auctions.prepareAuctionForNonOGChain(); } token.mint(_addresses[1], _importData[1]); emit ImportReceiptLog(_addresses[1], _importData[1], _importData[2], _extraData, auctions.currentTick(), importSequence, _burnHashes[1], _burnHashes[0], auctions.dailyMintable(), now, msg.sender); importSequence++; chainLedger.registerImport(_originChain, _destinationChain, _importData[1]); return true; } /// @notice Export MET tokens from this chain to another chain. /// @param tokenOwner Owner of the token, whose tokens are being exported. /// @param _destChain Destination chain for exported tokens /// @param _destMetronomeAddr Metronome address on destination chain /// @param _destRecipAddr Recipient address on the destination chain /// @param _amount Amount of token being exported /// @param _extraData Extra data for this export /// @return boolean true/false based on the outcome of export function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool) { require(msg.sender == address(token)); require(_destChain != 0x0 && _destMetronomeAddr != 0x0 && _destRecipAddr != 0x0 && _amount != 0); require(destinationChains[_destChain] == _destMetronomeAddr); require(token.balanceOf(tokenOwner) >= _amount.add(_fee)); token.destroy(tokenOwner, _amount.add(_fee)); uint dailyMintable = auctions.dailyMintable(); uint currentTick = auctions.currentTick(); if (burnSequence == 1) { exportedBurns.push(keccak256(uint8(0))); } if (_destChain == auctions.chain()) { claimables[_destMetronomeAddr][_destRecipAddr] = claimables[_destMetronomeAddr][_destRecipAddr].add(_amount); } uint blockTime = block.timestamp; bytes32 currentBurn = keccak256( blockTime, auctions.chain(), _destChain, _destMetronomeAddr, _destRecipAddr, _amount, currentTick, auctions.genesisTime(), dailyMintable, token.totalSupply(), _extraData, exportedBurns[burnSequence - 1]); exportedBurns.push(currentBurn); supplyOnAllChains[0] = token.totalSupply(); emit ExportReceiptLog(_destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData, currentTick, burnSequence, currentBurn, exportedBurns[burnSequence - 1], dailyMintable, supplyOnAllChains, auctions.genesisTime(), blockTime, auctions.dailyAuctionStartTime()); burnSequence = burnSequence + 1; chainLedger.registerExport(auctions.chain(), _destChain, _amount); return true; } } contract ChainLedger is Owned { using SafeMath for uint; mapping (bytes8 => uint) public balance; mapping (bytes8 => bool) public validChain; bytes8[] public chains; address public tokenPorter; Auctions public auctions; event LogRegisterChain(address indexed caller, bytes8 indexed chain, uint supply, bool outcome); event LogRegisterExport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount); event LogRegisterImport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount); function initChainLedger(address _tokenPorter, address _auctionsAddr) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); require(_auctionsAddr != 0x0); tokenPorter = _tokenPorter; auctions = Auctions(_auctionsAddr); return true; } function registerChain(bytes8 chain, uint supply) public onlyOwner returns (bool) { require(!validChain[chain]); validChain[chain] = true; chains.push(chain); balance[chain] = supply; emit LogRegisterChain(msg.sender, chain, supply, true); } function registerExport(bytes8 originChain, bytes8 destChain, uint amount) public { require(msg.sender == tokenPorter || msg.sender == owner); require(validChain[originChain] && validChain[destChain]); require(balance[originChain] >= amount); balance[originChain] = balance[originChain].sub(amount); balance[destChain] = balance[destChain].add(amount); emit LogRegisterExport(msg.sender, originChain, destChain, amount); } function registerImport(bytes8 originChain, bytes8 destChain, uint amount) public { require(msg.sender == tokenPorter || msg.sender == owner); require(validChain[originChain] && validChain[destChain]); balance[originChain] = balance[originChain].sub(amount); balance[destChain] = balance[destChain].add(amount); emit LogRegisterImport(msg.sender, originChain, destChain, amount); } } contract Validator is Owned { mapping (bytes32 => mapping (address => bool)) public hashAttestations; mapping (address => bool) public isValidator; mapping (address => uint8) public validatorNum; address[] public validators; address public metToken; address public tokenPorter; mapping (bytes32 => bool) public hashClaimed; uint8 public threshold = 2; event LogAttestation(bytes32 indexed hash, address indexed who, bool isValid); /// @param _validator1 first validator /// @param _validator2 second validator /// @param _validator3 third validator function initValidator(address _validator1, address _validator2, address _validator3) public onlyOwner { // Clear old validators. Validators can be updated multiple times for (uint8 i = 0; i < validators.length; i++) { delete isValidator[validators[i]]; delete validatorNum[validators[i]]; } delete validators; validators.push(_validator1); validators.push(_validator2); validators.push(_validator3); // TODO: This will be NA, Bloq and a third party (escrow or company) at launch, // and should be scripted into deploy isValidator[_validator1] = true; isValidator[_validator2] = true; isValidator[_validator3] = true; validatorNum[_validator1] = 0; validatorNum[_validator2] = 1; validatorNum[_validator3] = 2; } /// @notice set address of token porter /// @param _tokenPorter address of token porter function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); tokenPorter = _tokenPorter; return true; } function validateHash(bytes32 hash) public { require(isValidator[msg.sender]); hashAttestations[hash][msg.sender] = true; emit LogAttestation(hash, msg.sender, true); } function invalidateHash(bytes32 hash) public { require(isValidator[msg.sender]); hashAttestations[hash][msg.sender] = false; emit LogAttestation(hash, msg.sender, false); } function hashClaimable(bytes32 hash) public view returns(bool) { if (hashClaimed[hash]) { return false; } uint8 count = 0; for (uint8 i = 0; i < validators.length; i++) { if (hashAttestations[hash][validators[i]]) { count++;} } if (count >= threshold) { return true; } return false; } function claimHash(bytes32 hash) public { require(msg.sender == tokenPorter); require(hashClaimable(hash)); hashClaimed[hash] = true; } function isReceiptClaimable(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChain, uint[] _importData, bytes _proof) public view returns(bool) { // We want to validate that these hash to the provided hash as a safety check, // then we want to know if the hash is Claimable. // Due to stack too deep error and limitation in using number of local // variables we have to use uint array here. // _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee, // _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, // _importData[5] is _dailyMintable, _importData[6] is _burnSequence, // _addresses[0] is _destMetronomeAddr and _addresses[1] is _recipAddr require(_burnHashes[1] == keccak256(_importData[0], _originChain, _destinationChain, _addresses[0], _addresses[1], _importData[1], _importData[3], _importData[4], _importData[5], _supplyOnAllChain[0], _extraData, _burnHashes[0])); if (hashClaimable(_burnHashes[1])) { return true; } return false; } }
Return information about initial auction status.
function isInitialAuctionEnded() public view returns (bool) { return (initialAuctionEndTime != 0 && (now >= initialAuctionEndTime || token.totalSupply() >= INITIAL_SUPPLY)); }
624,348
./full_match/1/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/OrderCombiner.sol
Internal function to fulfill a group of validated orders, fully or partially, with an arbitrary number of items for offer and consideration per order and to execute transfers. Any order that is not currently active, has already been fully filled, or has been cancelled will be omitted. Remaining offer and consideration items will then be aggregated where possible as indicated by the supplied offer and consideration component arrays and aggregated items will be transferred to the fulfiller or to each intended recipient, respectively. Note that a failing item transfer or an issue with order formatting will cause the entire batch to fail. advancedOrders The orders to fulfill along with the fraction of those orders to attempt to fill. Note that both the offerer and the fulfiller must first approve this contract (or the conduit if indicated by the order) to transfer any relevant tokens on their behalf and that contracts must implement `onERC1155Received` in order to receive ERC1155 tokens as consideration. Also note that all offer and consideration components must have no remainder after multiplication of the respective amount with the supplied fraction for an order's partial fill amount to be considered valid. offerFulfillments An array of FulfillmentComponent arrays indicating which offer items to attempt to aggregate when preparing executions. considerationFulfillments An array of FulfillmentComponent arrays indicating which consideration items to attempt to aggregate when preparing executions. fulfillerConduitKey A bytes32 value indicating what conduit, if any, to source the fulfiller's token approvals from. The zero hash signifies that no conduit should be used, with direct approvals set on Consideration. recipient The intended recipient for all items that do not already have a designated recipient and are not already used as part of a provided fulfillment. orderHashes An array of order hashes for each order. containsNonOpen A boolean indicating whether any restricted or contract orders are present within the provided array of advanced orders. return availableOrders An array of booleans indicating if each order with an index corresponding to the index of the returned boolean was fulfillable or not. return executions An array of elements indicating the sequence of transfers performed as part of matching the given orders./ Retrieve length of offer fulfillments array and place on the stack. Retrieve length of consideration fulfillments array & place on stack. Allocate an execution for each offer and consideration fulfillment. Skip overflow checks as all for loops are indexed starting at zero. Track number of filtered executions. Iterate over each offer fulfillment. Derive aggregated execution corresponding with fulfillment. If the execution is filterable... Increment total filtered executions. Otherwise, assign the execution to the executions array. Iterate over each consideration fulfillment. Derive aggregated execution corresponding with fulfillment. If the execution is filterable... Increment total filtered executions. Otherwise, assign the execution to the executions array. If some number of executions have been filtered... reduce the total length of the executions array. Revert if no orders are available.
function _executeAvailableFulfillments( AdvancedOrder[] memory advancedOrders, FulfillmentComponent[][] memory offerFulfillments, FulfillmentComponent[][] memory considerationFulfillments, bytes32 fulfillerConduitKey, address recipient, bytes32[] memory orderHashes, bool containsNonOpen ) internal returns (bool[] memory availableOrders, Execution[] memory executions) { uint256 totalOfferFulfillments = offerFulfillments.length; uint256 totalConsiderationFulfillments = (considerationFulfillments.length); executions = new Execution[]( totalOfferFulfillments + totalConsiderationFulfillments ); unchecked { uint256 totalFilteredExecutions = 0; for (uint256 i = 0; i < totalOfferFulfillments;) { Execution memory execution = _aggregateAvailable( advancedOrders, Side.OFFER, offerFulfillments[i], fulfillerConduitKey, recipient ); if (_isFilterableExecution(execution)) { ++totalFilteredExecutions; executions[i - totalFilteredExecutions] = execution; } } for (uint256 i = 0; i < totalConsiderationFulfillments;) { Execution memory execution = _aggregateAvailable( advancedOrders, Side.CONSIDERATION, considerationFulfillments[i], fulfillerConduitKey, ); if (_isFilterableExecution(execution)) { ++totalFilteredExecutions; executions[i + totalOfferFulfillments - totalFilteredExecutions] = execution; } } if (totalFilteredExecutions != 0) { assembly { mstore(executions, sub(mload(executions), totalFilteredExecutions)) } } } if (executions.length == 0) { _revertNoSpecifiedOrdersAvailable(); } _performFinalChecksAndExecuteOrders(advancedOrders, executions, orderHashes, recipient, containsNonOpen); return (availableOrders, executions); }
9,675,823
./full_match/4/0x128d94BcA6df040739AF522759fc53D5D87C52f4/sources/browser/CloverNFT.sol
Mint a new token to multiple addresses
function mintNewTokenToMultipleAddresses(address[] memory _addresses, uint _amount) public { require(msg.sender == _owner || _isMinter(msg.sender),"Only owner and minters can mint tokens"); _mint(_addresses[0], _tokenCount, _amount, ""); for(uint8 i = 1; i <= _addresses.length-1; i++){ _mint(_addresses[i], _tokenCount, _amount, ""); } _author[_tokenCount] = msg.sender; _tokenCount++; }
674,316
./full_match/1/0x20FD177e08F024429545144734977d5b102BF01D/sources/contracts/ShillingTokenClaims.sol
Ensure claiming is allowed Ensure the account has unclaimed rewards Calculate the balance of the contract's token holdings Calculate the reward to be transferred to the account in wei Ensure the contract has sufficient tokens to cover the reward Transfer the reward tokens to the account Emit a Claimed event to indicate a successful claim
function _claim(uint256 unclaimedAmount, uint256 claimAmount) private { if (!claimAllowed) revert ClaimNotAllowed(); if (claimAmount <= 0 || claimAmount > unclaimedAmount) revert AddressHasNotEnoughClaims(); uint256 balance = uint256(tokenContract.balanceOf(address(this))); uint256 rewardWei = claimAmount * 10 ** 18; if (rewardWei > balance) revert InsufficientTokens(); tokenContract.transfer(_msgSender(), rewardWei); emit Claimed(_msgSender(), claimAmount); }
17,147,175
./full_match/1285/0x517f5D5f94d2F6FAa48AD889467cCF470064Ba43/sources/src/Libraries/LibUtil.sol
If the _res length is less than 68, then the transaction failed silently (without a revert message)
function getRevertMsg(bytes memory _res) internal pure returns (string memory) { if (_res.length < 68) return "Transaction reverted silently"; }
833,945
//SPDX-License-Identifier: MIT pragma solidity ^0.6.8; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // for WETH import "@nomiclabs/buidler/console.sol"; import './uniswapv2/interfaces/IUniswapV2Factory.sol'; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; contract FeeApprover is OwnableUpgradeSafe { using SafeMath for uint256; function initialize( address _COREAddress, address _WETHAddress, address _uniswapFactory ) public initializer { OwnableUpgradeSafe.__Ownable_init(); coreTokenAddress = _COREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = IUniswapV2Factory(_uniswapFactory).getPair(WETHAddress,coreTokenAddress); feePercentX100 = 10; paused = true; // We start paused until sync post LGE happens. } address tokenUniswapPair; IUniswapV2Factory public uniswapFactory; address internal WETHAddress; address coreTokenAddress; address coreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // CORE token is pausable function setPaused(bool _pause) public onlyOwner { paused = _pause; } function setFeeMultiplier(uint8 _feeMultiplier) public onlyOwner { feePercentX100 = _feeMultiplier; } function setCoreVaultAddress(address _coreVaultAddress) public onlyOwner { coreVaultAddress = _coreVaultAddress; } function sync() public { uint256 _LPSupplyOfPairTotal = IERC20(tokenUniswapPair).totalSupply(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function calculateAmountsAfterFee( address sender, address recipient, // unusued maybe use in future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = IERC20(tokenUniswapPair).totalSupply(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == coreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when corevault is sending, or infinite loop console.log("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console.log("Normal fee transfer"); transferToFeeDistributorAmount = amount.mul(feePercentX100).div(1000); transferToAmount = amount.sub(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
console.log("sender is " , sender); console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); console.log("Old LP supply", lastTotalSupplyOfLPTokens); console.log("Current LP supply", _LPSupplyOfPairTotal); console.log('Sender is pair' , sender == tokenUniswapPair); console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
function calculateAmountsAfterFee( address sender, uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = IERC20(tokenUniswapPair).totalSupply(); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); transferToFeeDistributorAmount = 0; transferToAmount = amount; }
12,562,845
./full_match/80001/0xA6BFBB4d45D1699df93431D1E093Df6B660Fa6A4/sources/project_/contracts/Vault.sol
_tradeId - index location in allTrades[] _tradeIndex - index location in userOpenTrades
function closeOrder(uint _tradeId, address _trader) public returns(int) { int collateral = tradingStorage.getOpenTradeDetails(_tradeId, _trader).collateral; int profit = marketTradingControl.closeMarketOrder(_tradeId, _trader); int pnl = collateral + profit; if(pnl > 0) DAI.transfer(_trader, uint(pnl)); vaultBalancing(); return pnl; }
860,879
/** *Submitted for verification at Etherscan.io on 2020-11-04 */ // File: contracts/spec_interfaces/ICertification.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @title Certification contract interface interface ICertification /* is Ownable */ { event GuardianCertificationUpdate(address indexed guardian, bool isCertified); /* * External methods */ /// Returns the certification status of a guardian /// @param guardian is the guardian to query function isGuardianCertified(address guardian) external view returns (bool isCertified); /// Sets the guardian certification status /// @dev governance function called only by the certification manager /// @param guardian is the guardian to update /// @param isCertified bool indication whether the guardian is certified function setGuardianCertification(address guardian, bool isCertified) external /* onlyCertificationManager */ ; } // File: contracts/spec_interfaces/IElections.sol pragma solidity 0.6.12; /// @title Elections contract interface interface IElections { // Election state change events event StakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, uint256 effectiveStake); event GuardianStatusUpdated(address indexed guardian, bool readyToSync, bool readyForCommittee); // Vote out / Vote unready event GuardianVotedUnready(address indexed guardian); event VoteUnreadyCasted(address indexed voter, address indexed subject, uint256 expiration); event GuardianVotedOut(address indexed guardian); event VoteOutCasted(address indexed voter, address indexed subject); /* * External functions */ /// Notifies that the guardian is ready to sync with other nodes /// @dev may be called with either the guardian address or the guardian's orbs address /// @dev ready to sync state is not managed in the contract that only emits an event /// @dev readyToSync clears the readyForCommittee state function readyToSync() external; /// Notifies that the guardian is ready to join the committee /// @dev may be called with either the guardian address or the guardian's orbs address /// @dev a qualified guardian calling readyForCommittee is added to the committee function readyForCommittee() external; /// Checks if a guardian is qualified to join the committee /// @dev when true, calling readyForCommittee() will result in adding the guardian to the committee /// @dev called periodically by guardians to check if they are qualified to join the committee /// @param guardian is the guardian to check /// @return canJoin indicating that the guardian can join the current committee function canJoinCommittee(address guardian) external view returns (bool); /// Returns an address effective stake /// The effective stake is derived from a guardian delegate stake and selfs stake /// @return effectiveStake is the guardian's effective stake function getEffectiveStake(address guardian) external view returns (uint effectiveStake); /// Returns the current committee along with the guardians' Orbs address and IP /// @return committee is a list of the committee members' guardian addresses /// @return weights is a list of the committee members' weight (effective stake) /// @return orbsAddrs is a list of the committee members' orbs address /// @return certification is a list of bool indicating the committee members certification /// @return ips is a list of the committee members' ip function getCommittee() external view returns (address[] memory committee, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips); // Vote-unready /// Casts an unready vote on a subject guardian /// @dev Called by a guardian as part of the automatic vote-unready flow /// @dev The transaction may be sent from the guardian or orbs address. /// @param subject is the subject guardian to vote out /// @param voteExpiration is the expiration time of the vote unready to prevent counting of a vote that is already irrelevant. function voteUnready(address subject, uint voteExpiration) external; /// Returns the current vote unready vote for a voter and a subject pair /// @param voter is the voting guardian address /// @param subject is the subject guardian address /// @return valid indicates whether there is a valid vote /// @return expiration returns the votes expiration time function getVoteUnreadyVote(address voter, address subject) external view returns (bool valid, uint256 expiration); /// Returns the current vote-unready status of a subject guardian. /// @dev the committee and certification data is used to check the certified and committee threshold /// @param subject is the subject guardian address /// @return committee is a list of the current committee members /// @return weights is a list of the current committee members weight /// @return certification is a list of bool indicating the committee members certification /// @return votes is a list of bool indicating the members that votes the subject unready /// @return subjectInCommittee indicates that the subject is in the committee /// @return subjectInCertifiedCommittee indicates that the subject is in the certified committee function getVoteUnreadyStatus(address subject) external view returns ( address[] memory committee, uint256[] memory weights, bool[] memory certification, bool[] memory votes, bool subjectInCommittee, bool subjectInCertifiedCommittee ); // Vote-out /// Casts a voteOut vote by the sender to the given address /// @dev the transaction is sent from the guardian address /// @param subject is the subject guardian address function voteOut(address subject) external; /// Returns the subject address the addr has voted-out against /// @param voter is the voting guardian address /// @return subject is the subject the voter has voted out function getVoteOutVote(address voter) external view returns (address); /// Returns the governance voteOut status of a guardian. /// @dev A guardian is voted out if votedStake / totalDelegatedStake (in percent mille) > threshold /// @param subject is the subject guardian address /// @return votedOut indicates whether the subject was voted out /// @return votedStake is the total stake voting against the subject /// @return totalDelegatedStake is the total delegated stake function getVoteOutStatus(address subject) external view returns (bool votedOut, uint votedStake, uint totalDelegatedStake); /* * Notification functions from other PoS contracts */ /// Notifies a delegated stake change event /// @dev Called by: delegation contract /// @param delegate is the delegate to update /// @param selfDelegatedStake is the delegate self stake (0 if not self-delegating) /// @param delegatedStake is the delegate delegated stake (0 if not self-delegating) /// @param totalDelegatedStake is the total delegated stake function delegatedStakeChange(address delegate, uint256 selfDelegatedStake, uint256 delegatedStake, uint256 totalDelegatedStake) external /* onlyDelegationsContract onlyWhenActive */; /// Notifies a new guardian was unregistered /// @dev Called by: guardian registration contract /// @dev when a guardian unregisters its status is updated to not ready to sync and is removed from the committee /// @param guardian is the address of the guardian that unregistered function guardianUnregistered(address guardian) external /* onlyGuardiansRegistrationContract */; /// Notifies on a guardian certification change /// @dev Called by: guardian registration contract /// @param guardian is the address of the guardian to update /// @param isCertified indicates whether the guardian is certified function guardianCertificationChanged(address guardian, bool isCertified) external /* onlyCertificationContract */; /* * Governance functions */ event VoteUnreadyTimeoutSecondsChanged(uint32 newValue, uint32 oldValue); event VoteOutPercentMilleThresholdChanged(uint32 newValue, uint32 oldValue); event VoteUnreadyPercentMilleThresholdChanged(uint32 newValue, uint32 oldValue); event MinSelfStakePercentMilleChanged(uint32 newValue, uint32 oldValue); /// Sets the minimum self stake requirement for the effective stake /// @dev governance function called only by the functional manager /// @param minSelfStakePercentMille is the minimum self stake in percent-mille (0-100,000) function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) external /* onlyFunctionalManager */; /// Returns the minimum self-stake required for the effective stake /// @return minSelfStakePercentMille is the minimum self stake in percent-mille function getMinSelfStakePercentMille() external view returns (uint32); /// Sets the vote-out threshold /// @dev governance function called only by the functional manager /// @param voteOutPercentMilleThreshold is the minimum threshold in percent-mille (0-100,000) function setVoteOutPercentMilleThreshold(uint32 voteOutPercentMilleThreshold) external /* onlyFunctionalManager */; /// Returns the vote-out threshold /// @return voteOutPercentMilleThreshold is the minimum threshold in percent-mille function getVoteOutPercentMilleThreshold() external view returns (uint32); /// Sets the vote-unready threshold /// @dev governance function called only by the functional manager /// @param voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille (0-100,000) function setVoteUnreadyPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) external /* onlyFunctionalManager */; /// Returns the vote-unready threshold /// @return voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille function getVoteUnreadyPercentMilleThreshold() external view returns (uint32); /// Returns the contract's settings /// @return minSelfStakePercentMille is the minimum self stake in percent-mille /// @return voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille /// @return voteOutPercentMilleThreshold is the minimum threshold in percent-mille function getSettings() external view returns ( uint32 minSelfStakePercentMille, uint32 voteUnreadyPercentMilleThreshold, uint32 voteOutPercentMilleThreshold ); /// Initializes the ready for committee notification for the committee guardians /// @dev governance function called only by the initialization admin during migration /// @dev identical behaviour as if each guardian sent readyForCommittee() /// @param guardians a list of guardians addresses to update function initReadyForCommittee(address[] calldata guardians) external /* onlyInitializationAdmin */; } // File: contracts/spec_interfaces/IManagedContract.sol pragma solidity 0.6.12; /// @title managed contract interface, used by the contracts registry to notify the contract on updates interface IManagedContract /* is ILockable, IContractRegistryAccessor, Initializable */ { /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external; } // File: contracts/spec_interfaces/IContractRegistry.sol pragma solidity 0.6.12; /// @title Contract registry contract interface /// @dev The contract registry holds Orbs PoS contracts and managers lists /// @dev The contract registry updates the managed contracts on changes in the contract list /// @dev Governance functions restricted to managers access the registry to retrieve the manager address /// @dev The contract registry represents the source of truth for Orbs Ethereum contracts /// @dev By tracking the registry events or query before interaction, one can access the up to date contracts interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr, bool managedContract); event ManagerChanged(string role, address newManager); event ContractRegistryUpdated(address newContractRegistry); /* * External functions */ /// Updates the contracts address and emits a corresponding event /// @dev governance function called only by the migrationManager or registryAdmin /// @param contractName is the contract name, used to identify it /// @param addr is the contract updated address /// @param managedContract indicates whether the contract is managed by the registry and notified on changes function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdminOrMigrationManager */; /// Returns the current address of the given contracts /// @param contractName is the contract name, used to identify it /// @return addr is the contract updated address function getContract(string calldata contractName) external view returns (address); /// Returns the list of contract addresses managed by the registry /// @dev Managed contracts are updated on changes in the registry contracts addresses /// @return addrs is the list of managed contracts function getManagedContracts() external view returns (address[] memory); /// Locks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin /// @dev When set all onlyWhenActive functions will revert function lockContracts() external /* onlyAdminOrMigrationManager */; /// Unlocks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin function unlockContracts() external /* onlyAdminOrMigrationManager */; /// Updates a manager address and emits a corresponding event /// @dev governance function called only by the registryAdmin /// @dev the managers list is a flexible list of role to the manager's address /// @param role is the managers' role name, for example "functionalManager" /// @param manager is the manager updated address function setManager(string calldata role, address manager) external /* onlyAdmin */; /// Returns the current address of the given manager /// @param role is the manager name, used to identify it /// @return addr is the manager updated address function getManager(string calldata role) external view returns (address); /// Sets a new contract registry to migrate to /// @dev governance function called only by the registryAdmin /// @dev updates the registry address record in all the managed contracts /// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts /// @param newRegistry is the new registry contract function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; /// Returns the previous contract registry address /// @dev used when the setting the contract as a new registry to assure a valid registry /// @return previousContractRegistry is the previous contract registry function getPreviousContractRegistry() external view returns (address); } // File: contracts/spec_interfaces/IContractRegistryAccessor.sol pragma solidity 0.6.12; interface IContractRegistryAccessor { /// Sets the contract registry address /// @dev governance function called only by an admin /// @param newRegistry is the new registry contract function setContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; /// Returns the contract registry address /// @return contractRegistry is the contract registry address function getContractRegistry() external view returns (IContractRegistry contractRegistry); function setRegistryAdmin(address _registryAdmin) external /* onlyInitializationAdmin */; } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/WithClaimableRegistryManagement.sol pragma solidity 0.6.12; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableRegistryManagement is Context { address private _registryAdmin; address private _pendingRegistryAdmin; event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin); /** * @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin. */ constructor () internal { address msgSender = _msgSender(); _registryAdmin = msgSender; emit RegistryManagementTransferred(address(0), msgSender); } /** * @dev Returns the address of the current registryAdmin. */ function registryAdmin() public view returns (address) { return _registryAdmin; } /** * @dev Throws if called by any account other than the registryAdmin. */ modifier onlyRegistryAdmin() { require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin"); _; } /** * @dev Returns true if the caller is the current registryAdmin. */ function isRegistryAdmin() public view returns (bool) { return _msgSender() == _registryAdmin; } /** * @dev Leaves the contract without registryAdmin. It will not be possible to call * `onlyManager` functions anymore. Can only be called by the current registryAdmin. * * NOTE: Renouncing registryManagement will leave the contract without an registryAdmin, * thereby removing any functionality that is only available to the registryAdmin. */ function renounceRegistryManagement() public onlyRegistryAdmin { emit RegistryManagementTransferred(_registryAdmin, address(0)); _registryAdmin = address(0); } /** * @dev Transfers registryManagement of the contract to a new account (`newManager`). */ function _transferRegistryManagement(address newRegistryAdmin) internal { require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address"); emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin); _registryAdmin = newRegistryAdmin; } /** * @dev Modifier throws if called by any account other than the pendingManager. */ modifier onlyPendingRegistryAdmin() { require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin"); _; } /** * @dev Allows the current registryAdmin to set the pendingManager address. * @param newRegistryAdmin The address to transfer registryManagement to. */ function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin { _pendingRegistryAdmin = newRegistryAdmin; } /** * @dev Allows the _pendingRegistryAdmin address to finalize the transfer. */ function claimRegistryManagement() public onlyPendingRegistryAdmin { //inject PUBLIC FUNC TO EXTERNAL _transferRegistryManagement(_pendingRegistryAdmin); _pendingRegistryAdmin = address(0); } /** * @dev Returns the current pendingRegistryAdmin */ function pendingRegistryAdmin() public view returns (address) { return _pendingRegistryAdmin; } } // File: contracts/Initializable.sol pragma solidity 0.6.12; contract Initializable { address private _initializationAdmin; event InitializationComplete(); /// Constructor /// Sets the initializationAdmin to the contract deployer /// The initialization admin may call any manager only function until initializationComplete constructor() public{ _initializationAdmin = msg.sender; } modifier onlyInitializationAdmin() { require(msg.sender == initializationAdmin(), "sender is not the initialization admin"); _; } /* * External functions */ /// Returns the initializationAdmin address function initializationAdmin() public view returns (address) { return _initializationAdmin; } /// Finalizes the initialization and revokes the initializationAdmin role function initializationComplete() public onlyInitializationAdmin { //inject PUBLIC FUNC TO EXTERNAL _initializationAdmin = address(0); emit InitializationComplete(); } /// Checks if the initialization was completed function isInitializationComplete() public view returns (bool) { return _initializationAdmin == address(0); } } // File: contracts/ContractRegistryAccessor.sol pragma solidity 0.6.12; contract ContractRegistryAccessor is IContractRegistryAccessor, WithClaimableRegistryManagement, Initializable { IContractRegistry private contractRegistry; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) public { require(address(_contractRegistry) != address(0), "_contractRegistry cannot be 0"); setContractRegistry(_contractRegistry); _transferRegistryManagement(_registryAdmin); } modifier onlyAdmin { require(isAdmin(), "sender is not an admin (registryManger or initializationAdmin)"); _; } modifier onlyMigrationManager { require(isMigrationManager(), "sender is not the migration manager"); _; } modifier onlyFunctionalManager { require(isFunctionalManager(), "sender is not the functional manager"); _; } /// Checks whether the caller is Admin: either the contract registry, the registry admin, or the initialization admin function isAdmin() internal view returns (bool) { return msg.sender == address(contractRegistry) || msg.sender == registryAdmin() || msg.sender == initializationAdmin(); } /// Checks whether the caller is a specific manager role or and Admin /// @dev queries the registry contract for the up to date manager assignment function isManager(string memory role) internal view returns (bool) { IContractRegistry _contractRegistry = contractRegistry; return isAdmin() || _contractRegistry != IContractRegistry(0) && contractRegistry.getManager(role) == msg.sender; } /// Checks whether the caller is the migration manager function isMigrationManager() internal view returns (bool) { return isManager('migrationManager'); } /// Checks whether the caller is the functional manager function isFunctionalManager() internal view returns (bool) { return isManager('functionalManager'); } /* * Contract getters, return the address of a contract by calling the contract registry */ function getProtocolContract() internal view returns (address) { return contractRegistry.getContract("protocol"); } function getStakingRewardsContract() internal view returns (address) { return contractRegistry.getContract("stakingRewards"); } function getFeesAndBootstrapRewardsContract() internal view returns (address) { return contractRegistry.getContract("feesAndBootstrapRewards"); } function getCommitteeContract() internal view returns (address) { return contractRegistry.getContract("committee"); } function getElectionsContract() internal view returns (address) { return contractRegistry.getContract("elections"); } function getDelegationsContract() internal view returns (address) { return contractRegistry.getContract("delegations"); } function getGuardiansRegistrationContract() internal view returns (address) { return contractRegistry.getContract("guardiansRegistration"); } function getCertificationContract() internal view returns (address) { return contractRegistry.getContract("certification"); } function getStakingContract() internal view returns (address) { return contractRegistry.getContract("staking"); } function getSubscriptionsContract() internal view returns (address) { return contractRegistry.getContract("subscriptions"); } function getStakingRewardsWallet() internal view returns (address) { return contractRegistry.getContract("stakingRewardsWallet"); } function getBootstrapRewardsWallet() internal view returns (address) { return contractRegistry.getContract("bootstrapRewardsWallet"); } function getGeneralFeesWallet() internal view returns (address) { return contractRegistry.getContract("generalFeesWallet"); } function getCertifiedFeesWallet() internal view returns (address) { return contractRegistry.getContract("certifiedFeesWallet"); } function getStakingContractHandler() internal view returns (address) { return contractRegistry.getContract("stakingContractHandler"); } /* * Governance functions */ event ContractRegistryAddressUpdated(address addr); /// Sets the contract registry address /// @dev governance function called only by an admin /// @param newContractRegistry is the new registry contract function setContractRegistry(IContractRegistry newContractRegistry) public override onlyAdmin { require(newContractRegistry.getPreviousContractRegistry() == address(contractRegistry), "new contract registry must provide the previous contract registry"); contractRegistry = newContractRegistry; emit ContractRegistryAddressUpdated(address(newContractRegistry)); } /// Returns the contract registry that the contract is set to use /// @return contractRegistry is the registry contract address function getContractRegistry() public override view returns (IContractRegistry) { return contractRegistry; } function setRegistryAdmin(address _registryAdmin) public override onlyInitializationAdmin { //inject PUBLIC FUNC TO EXTERNAL _transferRegistryManagement(_registryAdmin); } } // File: contracts/spec_interfaces/ILockable.sol pragma solidity 0.6.12; /// @title lockable contract interface, allows to lock a contract interface ILockable { event Locked(); event Unlocked(); /// Locks the contract to external non-governance function calls /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon locking all managed contracts /// @dev getters and migration functions remain active also for locked contracts /// @dev checked by the onlyWhenActive modifier function lock() external /* onlyMigrationManager */; /// Unlocks the contract /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon unlocking all managed contracts function unlock() external /* onlyMigrationManager */; /// Returns the contract locking status /// @return isLocked is a bool indicating the contract is locked function isLocked() view external returns (bool); } // File: contracts/Lockable.sol pragma solidity 0.6.12; /// @title lockable contract contract Lockable is ILockable, ContractRegistryAccessor { bool public locked; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public {} /// Locks the contract to external non-governance function calls /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon locking all managed contracts /// @dev getters and migration functions remain active also for locked contracts /// @dev checked by the onlyWhenActive modifier function lock() public override onlyMigrationManager { //inject PUBLIC FUNC TO EXTERNAL locked = true; emit Locked(); } /// Unlocks the contract /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon unlocking all managed contracts function unlock() public override onlyMigrationManager { //inject PUBLIC FUNC TO EXTERNAL locked = false; emit Unlocked(); } /// Returns the contract locking status /// @return isLocked is a bool indicating the contract is locked function isLocked() public override view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL return locked; } modifier onlyWhenActive() { require(!locked, "contract is locked for this operation"); _; } } // File: contracts/ManagedContract.sol pragma solidity 0.6.12; /// @title managed contract contract ManagedContract is IManagedContract, Lockable { /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) Lockable(_contractRegistry, _registryAdmin) public {} /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() virtual override public {} //inject PUBLIC FUNC TO EXTERNAL } // File: contracts/Certification.sol pragma solidity 0.6.12; /// @title Certification contract contract Certification is ICertification, ManagedContract { mapping(address => bool) guardianCertification; modifier onlyCertificationManager { require(isManager("certificationManager"), "sender is not the certification manager"); _; } /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) ManagedContract(_contractRegistry, _registryAdmin) public {} /* * External functions */ /// Returns the certification status of a guardian /// @param guardian is the guardian to query function isGuardianCertified(address guardian) public override view returns (bool isCertified) { //inject PUBLIC FUNC TO EXTERNAL return guardianCertification[guardian]; } /// Sets the guardian certification status /// @dev governance function called only by the certification manager /// @param guardian is the guardian to update /// @param isCertified bool indication whether the guardian is certified function setGuardianCertification(address guardian, bool isCertified) public override onlyCertificationManager onlyWhenActive { //inject PUBLIC FUNC TO EXTERNAL guardianCertification[guardian] = isCertified; emit GuardianCertificationUpdate(guardian, isCertified); electionsContract.guardianCertificationChanged(guardian, isCertified); } /* * Contracts topology / registry interface */ IElections electionsContract; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() public override { //inject PUBLIC FUNC TO EXTERNAL electionsContract = IElections(getElectionsContract()); } }
Elections contract interface Election state change events Vote out / Vote unready Vote-unready Vote-out
interface IElections { event StakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, uint256 effectiveStake); event GuardianStatusUpdated(address indexed guardian, bool readyToSync, bool readyForCommittee); event GuardianVotedUnready(address indexed guardian); event VoteUnreadyCasted(address indexed voter, address indexed subject, uint256 expiration); event GuardianVotedOut(address indexed guardian); event VoteOutCasted(address indexed voter, address indexed subject); function readyToSync() external; function readyForCommittee() external; function canJoinCommittee(address guardian) external view returns (bool); function getEffectiveStake(address guardian) external view returns (uint effectiveStake); function getCommittee() external view returns (address[] memory committee, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips); function voteUnready(address subject, uint voteExpiration) external; function getVoteUnreadyVote(address voter, address subject) external view returns (bool valid, uint256 expiration); function getVoteUnreadyStatus(address subject) external view returns ( address[] memory committee, uint256[] memory weights, bool[] memory certification, bool[] memory votes, bool subjectInCommittee, bool subjectInCertifiedCommittee ); function voteOut(address subject) external; function getVoteOutVote(address voter) external view returns (address); function getVoteOutStatus(address subject) external view returns (bool votedOut, uint votedStake, uint totalDelegatedStake); function delegatedStakeChange(address delegate, uint256 selfDelegatedStake, uint256 delegatedStake, uint256 totalDelegatedStake) external /* onlyDelegationsContract onlyWhenActive */; function guardianUnregistered(address guardian) external /* onlyGuardiansRegistrationContract */; function guardianCertificationChanged(address guardian, bool isCertified) external /* onlyCertificationContract */; event VoteUnreadyTimeoutSecondsChanged(uint32 newValue, uint32 oldValue); event VoteOutPercentMilleThresholdChanged(uint32 newValue, uint32 oldValue); event VoteUnreadyPercentMilleThresholdChanged(uint32 newValue, uint32 oldValue); event MinSelfStakePercentMilleChanged(uint32 newValue, uint32 oldValue); function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) external /* onlyFunctionalManager */; function getMinSelfStakePercentMille() external view returns (uint32); function setVoteOutPercentMilleThreshold(uint32 voteOutPercentMilleThreshold) external /* onlyFunctionalManager */; function getVoteOutPercentMilleThreshold() external view returns (uint32); function setVoteUnreadyPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) external /* onlyFunctionalManager */; function getVoteUnreadyPercentMilleThreshold() external view returns (uint32); function getSettings() external view returns ( uint32 minSelfStakePercentMille, uint32 voteUnreadyPercentMilleThreshold, uint32 voteOutPercentMilleThreshold ); function initReadyForCommittee(address[] calldata guardians) external /* onlyInitializationAdmin */; } }
1,844,801
// SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./IVirtualBalanceWrapper.sol"; import "./IBaseReward.sol"; contract BaseReward is ReentrancyGuard, IBaseReward { using Address for address payable; using SafeMath for uint256; using SafeERC20 for IERC20; address public rewardToken; uint256 public constant duration = 7 days; // address public owner; mapping(address => bool) private owners; address public virtualBalance; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user); event Withdrawn(address indexed user); event RewardPaid(address indexed user, uint256 reward); event NewOwner(address indexed sender, address operator); event RemoveOwner(address indexed sender, address operator); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyOwners() { require(isOwner(msg.sender), "BaseReward: caller is not an owner"); _; } constructor( address _reward, address _virtualBalance, address _owner ) public { rewardToken = _reward; virtualBalance = _virtualBalance; owners[_owner] = true; } function totalSupply() public view returns (uint256) { return IVirtualBalanceWrapper(virtualBalance).totalSupply(); } function balanceOf(address _for) public view returns (uint256) { return IVirtualBalanceWrapper(virtualBalance).balanceOf(_for); } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view override returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function addOwner(address _newOwner) public override onlyOwners { require(!isOwner(_newOwner), "BaseReward: address is already owner"); owners[_newOwner] = true; emit NewOwner(msg.sender, _newOwner); } function addOwners(address[] calldata _newOwners) external override onlyOwners { for (uint256 i = 0; i < _newOwners.length; i++) { addOwner(_newOwners[i]); } } function removeOwner(address _owner) external override onlyOwners { require(isOwner(_owner), "BaseReward: address is not owner"); owners[_owner] = false; emit RemoveOwner(msg.sender, _owner); } function isOwner(address _owner) public view override returns (bool) { return owners[_owner]; } function stake(address _for) public override updateReward(_for) onlyOwners { emit Staked(_for); } function withdraw(address _for) public override updateReward(_for) onlyOwners { emit Withdrawn(_for); } function getReward(address _for) public override nonReentrant updateReward(_for) { uint256 reward = earned(_for); if (reward > 0) { rewards[_for] = 0; if (rewardToken != address(0)) { IERC20(rewardToken).safeTransfer(_for, reward); } else { require( address(this).balance >= reward, "BaseReward: !address(this).balance" ); payable(_for).sendValue(reward); } emit RewardPaid(_for, reward); } } function notifyRewardAmount(uint256 reward) external override updateReward(address(0)) onlyOwners { // overflow fix according to https://sips.synthetix.io/sips/sip-77 require( reward < uint256(-1) / 1e18, "the notified reward cannot invoke multiplication overflow" ); if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); emit RewardAdded(reward); } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; interface IVirtualBalanceWrapperFactory { function createWrapper(address _op) external returns (address); } interface IVirtualBalanceWrapper { function totalSupply() external view returns (uint256); function balanceOf(address _account) external view returns (uint256); function stakeFor(address _for, uint256 _amount) external returns (bool); function withdrawFor(address _for, uint256 amount) external returns (bool); } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; interface IBaseReward { function earned(address account) external view returns (uint256); function stake(address _for) external; function withdraw(address _for) external; function getReward(address _for) external; function notifyRewardAmount(uint256 reward) external; function addOwner(address _newOwner) external; function addOwners(address[] calldata _newOwners) external; function removeOwner(address _owner) external; function isOwner(address _owner) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/IVirtualBalanceWrapper.sol"; import "../common/BaseReward.sol"; contract SupplyRewardFactory { event NewOwner(address indexed sender, address operator); event RemoveOwner(address indexed sender, address operator); event CreateReward(address pool, address rewardToken); mapping(address => bool) private owners; modifier onlyOwners() { require( isOwner(msg.sender), "SupplyRewardFactory: caller is not an owner" ); _; } constructor() public { owners[msg.sender] = true; } function addOwner(address _newOwner) public onlyOwners { require( !isOwner(_newOwner), "SupplyRewardFactory: address is already owner" ); owners[_newOwner] = true; emit NewOwner(msg.sender, _newOwner); } function addOwners(address[] calldata _newOwners) external onlyOwners { for (uint256 i = 0; i < _newOwners.length; i++) { addOwner(_newOwners[i]); } } function removeOwner(address _owner) external onlyOwners { require(isOwner(_owner), "SupplyRewardFactory: address is not owner"); owners[_owner] = false; emit RemoveOwner(msg.sender, _owner); } function isOwner(address _owner) public view returns (bool) { return owners[_owner]; } function createReward( address _rewardToken, address _virtualBalance, address _owner ) public onlyOwners returns (address) { BaseReward pool = new BaseReward( _rewardToken, _virtualBalance, _owner ); emit CreateReward(address(pool), _rewardToken); return address(pool); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "./common/IVirtualBalanceWrapper.sol"; import "./supply/SupplyInterfaces.sol"; contract SupplyBooster is Initializable, ReentrancyGuard, ISupplyBooster { using Address for address payable; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public supplyRewardFactory; address public virtualBalanceWrapperFactory; address public extraReward; uint256 public launchTime; uint256 public version; address payable public teamFeeAddress; address public lendingMarket; address public owner; address public governance; struct PoolInfo { address underlyToken; address rewardInterestPool; address supplyTreasuryFund; address virtualBalance; bool isErc20; bool shutdown; } enum LendingInfoState { NONE, LOCK, UNLOCK, LIQUIDATE } struct LendingInfo { uint256 pid; address user; address underlyToken; uint256 lendingAmount; uint256 borrowNumbers; uint256 startedBlock; LendingInfoState state; } address public constant ZERO_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 public constant MIN_INTEREST_PERCENT = 0; uint256 public constant MAX_INTEREST_PERCENT = 100; uint256 public constant FEE_PERCENT = 10; uint256 public constant PERCENT_DENOMINATOR = 100; PoolInfo[] public override poolInfo; uint256 public interestPercent; mapping(uint256 => uint256) public frozenTokens; /* pool id => amount */ mapping(bytes32 => LendingInfo) public lendingInfos; mapping(uint256 => uint256) public interestTotal; event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); event Borrow( address indexed user, uint256 indexed pid, bytes32 indexed lendingId, uint256 lendingAmount, uint256 lendingInterest, uint256 borrowNumbers ); event RepayBorrow( bytes32 indexed lendingId, address indexed user, uint256 lendingAmount, uint256 lendingInterest, bool isErc20 ); event Liquidate( bytes32 indexed lendingId, uint256 lendingAmount, uint256 lendingInterest ); event Initialized(address indexed thisAddress); event ToggleShutdownPool(uint256 pid, bool shutdown); event SetOwner(address owner); event SetGovernance(address governance); modifier onlyOwner() { require(owner == msg.sender, "SupplyBooster: caller is not the owner"); _; } modifier onlyGovernance() { require( governance == msg.sender, "SupplyBooster: caller is not the governance" ); _; } modifier onlyLendingMarket() { require( lendingMarket == msg.sender, " SupplyBooster: caller is not the lendingMarket" ); _; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } /* The default governance user is GenerateLendingPools contract. It will be set to DAO in the future */ function setGovernance(address _governance) public onlyOwner { governance = _governance; emit SetGovernance(_governance); } function setLendingMarket(address _v) public onlyOwner { require(_v != address(0), "!_v"); lendingMarket = _v; } function setExtraReward(address _v) public onlyOwner { require(_v != address(0), "!_v"); extraReward = _v; } function initialize( address _owner, address _virtualBalanceWrapperFactory, address _supplyRewardFactory, address payable _teamFeeAddress ) public initializer { owner = _owner; governance = _owner; virtualBalanceWrapperFactory = _virtualBalanceWrapperFactory; supplyRewardFactory = _supplyRewardFactory; teamFeeAddress = _teamFeeAddress; launchTime = block.timestamp; version = 1; interestPercent = 50; emit Initialized(address(this)); } function addSupplyPool(address _underlyToken, address _supplyTreasuryFund) public override onlyGovernance returns (bool) { bool isErc20 = _underlyToken == ZERO_ADDRESS ? false : true; address virtualBalance = IVirtualBalanceWrapperFactory( virtualBalanceWrapperFactory ).createWrapper(address(this)); ISupplyTreasuryFund(_supplyTreasuryFund).initialize( virtualBalance, _underlyToken, isErc20 ); address rewardInterestPool; if (isErc20) { rewardInterestPool = ISupplyRewardFactory(supplyRewardFactory) .createReward(_underlyToken, virtualBalance, address(this)); } else { rewardInterestPool = ISupplyRewardFactory(supplyRewardFactory) .createReward(address(0), virtualBalance, address(this)); } if (extraReward != address(0)) { ISupplyPoolExtraReward(extraReward).addExtraReward( poolInfo.length, _underlyToken, virtualBalance, isErc20 ); } poolInfo.push( PoolInfo({ underlyToken: _underlyToken, rewardInterestPool: rewardInterestPool, supplyTreasuryFund: _supplyTreasuryFund, virtualBalance: virtualBalance, isErc20: isErc20, shutdown: false }) ); return true; } function updateSupplyTreasuryFund( uint256 _pid, address _supplyTreasuryFund, bool _setReward ) public onlyOwner nonReentrant { PoolInfo storage pool = poolInfo[_pid]; uint256 bal = ISupplyTreasuryFund(pool.supplyTreasuryFund).migrate( _supplyTreasuryFund, _setReward ); ISupplyTreasuryFund(_supplyTreasuryFund).initialize( pool.virtualBalance, pool.underlyToken, pool.isErc20 ); pool.supplyTreasuryFund = _supplyTreasuryFund; if (pool.isErc20) { sendToken(pool.underlyToken, pool.supplyTreasuryFund, bal); ISupplyTreasuryFund(pool.supplyTreasuryFund).depositFor( address(0), bal ); } else { ISupplyTreasuryFund(pool.supplyTreasuryFund).depositFor{value: bal}( address(0) ); } } function toggleShutdownPool(uint256 _pid) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; pool.shutdown = !pool.shutdown; if (extraReward != address(0)) { ISupplyPoolExtraReward(extraReward).toggleShutdownPool( _pid, pool.shutdown ); } emit ToggleShutdownPool(_pid, pool.shutdown); } function _deposit(uint256 _pid, uint256 _amount) internal nonReentrant { PoolInfo storage pool = poolInfo[_pid]; require(!pool.shutdown, "SupplyBooster: !shutdown"); require(_amount > 0, "SupplyBooster: !_amount"); if (!pool.isErc20) { require( msg.value == _amount, "SupplyBooster: !msg.value == _amount" ); } if (pool.isErc20) { IERC20(pool.underlyToken).safeTransferFrom( msg.sender, pool.supplyTreasuryFund, _amount ); ISupplyTreasuryFund(pool.supplyTreasuryFund).depositFor( msg.sender, _amount ); } else { ISupplyTreasuryFund(pool.supplyTreasuryFund).depositFor{ value: _amount }(msg.sender); } IBaseReward(pool.rewardInterestPool).stake(msg.sender); if (extraReward != address(0)) { ISupplyPoolExtraReward(extraReward).beforeStake(_pid, msg.sender); } IVirtualBalanceWrapper(pool.virtualBalance).stakeFor( msg.sender, _amount ); if (extraReward != address(0)) { ISupplyPoolExtraReward(extraReward).afterStake(_pid, msg.sender); } emit Deposited(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { _deposit(_pid, _amount); } function deposit(uint256 _pid) public payable { _deposit(_pid, msg.value); } function withdraw(uint256 _pid, uint256 _amount) public nonReentrant returns (bool) { PoolInfo storage pool = poolInfo[_pid]; uint256 depositAmount = IVirtualBalanceWrapper(pool.virtualBalance) .balanceOf(msg.sender); require(_amount <= depositAmount, "SupplyBooster: !depositAmount"); IBaseReward(pool.rewardInterestPool).withdraw(msg.sender); ISupplyTreasuryFund(pool.supplyTreasuryFund).withdrawFor( msg.sender, _amount ); if (extraReward != address(0)) { ISupplyPoolExtraReward(extraReward).beforeWithdraw( _pid, msg.sender ); } IVirtualBalanceWrapper(pool.virtualBalance).withdrawFor( msg.sender, _amount ); if (extraReward != address(0)) { ISupplyPoolExtraReward(extraReward).afterWithdraw(_pid, msg.sender); } emit Withdrawn(msg.sender, _pid, _amount); return true; } receive() external payable {} function claimTreasuryFunds() public nonReentrant { for (uint256 i = 0; i < poolInfo.length; i++) { if (poolInfo[i].shutdown) { continue; } uint256 interest = ISupplyTreasuryFund( poolInfo[i].supplyTreasuryFund ).claim(); if (interest > 0) { if (poolInfo[i].isErc20) { sendToken( poolInfo[i].underlyToken, poolInfo[i].rewardInterestPool, interest ); } else { sendToken( address(0), poolInfo[i].rewardInterestPool, interest ); } IBaseReward(poolInfo[i].rewardInterestPool).notifyRewardAmount( interest ); } } } function getRewards(uint256[] memory _pids) public nonReentrant { for (uint256 i = 0; i < _pids.length; i++) { PoolInfo storage pool = poolInfo[_pids[i]]; if (pool.shutdown) continue; ISupplyTreasuryFund(pool.supplyTreasuryFund).getReward(msg.sender); if (IBaseReward(pool.rewardInterestPool).earned(msg.sender) > 0) { IBaseReward(pool.rewardInterestPool).getReward(msg.sender); } if (extraReward != address(0)) { ISupplyPoolExtraReward(extraReward).getRewards( _pids[i], msg.sender ); } } } function setInterestPercent(uint256 _v) public onlyGovernance { require( _v >= MIN_INTEREST_PERCENT && _v <= MAX_INTEREST_PERCENT, "!_v" ); interestPercent = _v; } function setTeamFeeAddress(address _v) public { require(msg.sender == teamFeeAddress, "!teamAddress"); require(_v != address(0), "!_v"); teamFeeAddress = payable(_v); } function calculateAmount( uint256 _bal, bool _fee, bool _interest, bool _extra ) internal view returns ( uint256, uint256, uint256 ) { uint256 fee = _fee ? _bal.mul(FEE_PERCENT).div(PERCENT_DENOMINATOR) : 0; uint256 interest = _bal.sub(fee).mul(interestPercent).div( PERCENT_DENOMINATOR ); uint256 extra = _bal.sub(fee).sub(interest); if (!_extra) extra = 0; if (!_interest) interest = 0; return (fee, interest, extra); } function sendToken( address _token, address _receiver, uint256 _amount ) internal { if (_token == address(0) || _token == ZERO_ADDRESS) { payable(_receiver).sendValue(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } function sendBalanceEther( uint256 _pid, uint256 _bal, bool _fee, bool _interest, bool _extra ) internal { if (_bal == 0) return; PoolInfo storage pool = poolInfo[_pid]; (uint256 fee, uint256 interest, uint256 extra) = calculateAmount( _bal, _fee, _interest, _extra ); if (fee > 0) { sendToken(pool.underlyToken, teamFeeAddress, fee); } if (extraReward == address(0)) { interest = interest.add(extra); } else { ISupplyPoolExtraReward(extraReward).notifyRewardAmount{ value: extra }(_pid, address(0), extra); } if (interest > 0) { sendToken(pool.underlyToken, pool.rewardInterestPool, interest); IBaseReward(pool.rewardInterestPool).notifyRewardAmount(interest); } } function sendBalanceErc20( uint256 _pid, uint256 _bal, bool _fee, bool _interest, bool _extra ) internal { if (_bal == 0) return; PoolInfo storage pool = poolInfo[_pid]; (uint256 fee, uint256 interest, uint256 extra) = calculateAmount( _bal, _fee, _interest, _extra ); if (fee > 0) { sendToken(pool.underlyToken, teamFeeAddress, fee); } if (extraReward == address(0)) { interest = interest.add(extra); } else { sendToken(pool.underlyToken, extraReward, extra); ISupplyPoolExtraReward(extraReward).notifyRewardAmount( _pid, pool.underlyToken, extra ); } if (interest > 0) { sendToken(pool.underlyToken, pool.rewardInterestPool, interest); IBaseReward(pool.rewardInterestPool).notifyRewardAmount(interest); } } function _borrow( uint256 _pid, bytes32 _lendingId, address _user, uint256 _lendingAmount, uint256 _lendingInterest, uint256 _borrowNumbers ) internal { PoolInfo storage pool = poolInfo[_pid]; require(!pool.shutdown, "SupplyBooster: !shutdown"); ISupplyTreasuryFund(pool.supplyTreasuryFund).borrow( _user, _lendingAmount, _lendingInterest ); frozenTokens[_pid] = frozenTokens[_pid].add(_lendingAmount); interestTotal[_pid] = interestTotal[_pid].add(_lendingInterest); LendingInfo memory lendingInfo; lendingInfo.pid = _pid; lendingInfo.user = _user; lendingInfo.underlyToken = pool.underlyToken; lendingInfo.lendingAmount = _lendingAmount; lendingInfo.borrowNumbers = _borrowNumbers; lendingInfo.startedBlock = block.number; lendingInfo.state = LendingInfoState.LOCK; lendingInfos[_lendingId] = lendingInfo; if (pool.isErc20) { sendBalanceErc20( lendingInfo.pid, _lendingInterest, true, true, true ); } else { sendBalanceEther( lendingInfo.pid, _lendingInterest, true, true, true ); } emit Borrow( _user, _pid, _lendingId, _lendingAmount, _lendingInterest, _borrowNumbers ); } function borrow( uint256 _pid, bytes32 _lendingId, address _user, uint256 _lendingAmount, uint256 _lendingInterest, uint256 _borrowNumbers ) public override onlyLendingMarket nonReentrant { _borrow( _pid, _lendingId, _user, _lendingAmount, _lendingInterest, _borrowNumbers ); } function _repayBorrow( bytes32 _lendingId, address _user, uint256 _lendingAmount, uint256 _lendingInterest ) internal nonReentrant { LendingInfo storage lendingInfo = lendingInfos[_lendingId]; PoolInfo storage pool = poolInfo[lendingInfo.pid]; require( lendingInfo.state == LendingInfoState.LOCK, "SupplyBooster: !LOCK" ); require( _lendingAmount >= lendingInfo.lendingAmount, "SupplyBooster: !_lendingAmount" ); frozenTokens[lendingInfo.pid] = frozenTokens[lendingInfo.pid].sub( lendingInfo.lendingAmount ); interestTotal[lendingInfo.pid] = interestTotal[lendingInfo.pid].sub( _lendingInterest ); if (pool.isErc20) { sendToken( pool.underlyToken, pool.supplyTreasuryFund, lendingInfo.lendingAmount ); ISupplyTreasuryFund(pool.supplyTreasuryFund).repayBorrow( lendingInfo.lendingAmount ); } else { ISupplyTreasuryFund(pool.supplyTreasuryFund).repayBorrow{ value: lendingInfo.lendingAmount }(); } lendingInfo.state = LendingInfoState.UNLOCK; emit RepayBorrow( _lendingId, _user, _lendingAmount, _lendingInterest, pool.isErc20 ); } function repayBorrow( bytes32 _lendingId, address _user, uint256 _lendingInterest ) external payable override onlyLendingMarket { _repayBorrow(_lendingId, _user, msg.value, _lendingInterest); } function repayBorrow( bytes32 _lendingId, address _user, uint256 _lendingAmount, uint256 _lendingInterest ) external override onlyLendingMarket { _repayBorrow(_lendingId, _user, _lendingAmount, _lendingInterest); } function _liquidate(bytes32 _lendingId, uint256 _lendingInterest) internal returns (address) { LendingInfo storage lendingInfo = lendingInfos[_lendingId]; PoolInfo storage pool = poolInfo[lendingInfo.pid]; if (!pool.isErc20) { require( msg.value > 0, "SupplyBooster: msg.value must be greater than 0" ); } require( lendingInfo.state == LendingInfoState.LOCK, "SupplyBooster: !LOCK" ); frozenTokens[lendingInfo.pid] = frozenTokens[lendingInfo.pid].sub( lendingInfo.lendingAmount ); interestTotal[lendingInfo.pid] = interestTotal[lendingInfo.pid].sub( _lendingInterest ); if (pool.isErc20) { sendToken( pool.underlyToken, pool.supplyTreasuryFund, lendingInfo.lendingAmount ); ISupplyTreasuryFund(pool.supplyTreasuryFund).repayBorrow( lendingInfo.lendingAmount ); uint256 bal = IERC20(pool.underlyToken).balanceOf(address(this)); sendBalanceErc20(lendingInfo.pid, bal, true, true, true); } else { ISupplyTreasuryFund(pool.supplyTreasuryFund).repayBorrow{ value: lendingInfo.lendingAmount }(); uint256 bal = address(this).balance; sendBalanceEther(lendingInfo.pid, bal, true, true, true); } lendingInfo.state = LendingInfoState.LIQUIDATE; emit Liquidate(_lendingId, lendingInfo.lendingAmount, _lendingInterest); } function liquidate(bytes32 _lendingId, uint256 _lendingInterest) public payable override onlyLendingMarket nonReentrant returns (address) { return _liquidate(_lendingId, _lendingInterest); } /* view functions */ function poolLength() external view returns (uint256) { return poolInfo.length; } function getUtilizationRate(uint256 _pid) public view override returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBal = ISupplyTreasuryFund(pool.supplyTreasuryFund) .getBalance(); if (currentBal.add(frozenTokens[_pid]) == 0) { return 0; } return frozenTokens[_pid].mul(1e18).div( currentBal.add(frozenTokens[_pid]) ); } function getBorrowRatePerBlock(uint256 _pid) public view override returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return ISupplyTreasuryFund(pool.supplyTreasuryFund) .getBorrowRatePerBlock(); } function getLendingUnderlyToken(bytes32 _lendingId) public view override returns (address) { LendingInfo storage lendingInfo = lendingInfos[_lendingId]; return (lendingInfo.underlyToken); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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)); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; pragma experimental ABIEncoderV2; import "../common/IBaseReward.sol"; import "./ISupplyBooster.sol"; interface ISupplyPoolExtraReward { function addExtraReward( uint256 _pid, address _lpToken, address _virtualBalance, bool _isErc20) external; function toggleShutdownPool(uint256 _pid, bool _state) external; function getRewards(uint256 _pid,address _for) external; function beforeStake(uint256 _pid, address _for) external; function afterStake(uint256 _pid, address _for) external; function beforeWithdraw(uint256 _pid, address _for) external; function afterWithdraw(uint256 _pid, address _for) external; function notifyRewardAmount( uint256 _pid, address _underlyToken, uint256 _amount) external payable; } interface ISupplyTreasuryFund { function initialize(address _virtualBalance, address _underlyToken, bool _isErc20) external; function depositFor(address _for) external payable; function depositFor(address _for, uint256 _amount) external; function withdrawFor(address _to, uint256 _amount) external returns (uint256); function borrow(address _to, uint256 _lendingAmount,uint256 _lendingInterest) external returns (uint256); function repayBorrow() external payable; function repayBorrow(uint256 _lendingAmount) external; function claimComp(address _comp, address _comptroller, address _to) external returns (uint256, bool); function getBalance() external view returns (uint256); function getBorrowRatePerBlock() external view returns (uint256); function claim() external returns(uint256); function migrate(address _newTreasuryFund, bool _setReward) external returns(uint256); function getReward(address _for) external; } interface ISupplyRewardFactory { function createReward( address _rewardToken, address _virtualBalance, address _owner ) external returns (address); } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; interface ISupplyBooster { function poolInfo(uint256 _pid) external view returns ( address underlyToken, address rewardInterestPool, address supplyTreasuryFund, address virtualBalance, bool isErc20, bool shutdown ); function liquidate(bytes32 _lendingId, uint256 _lendingInterest) external payable returns (address); function getLendingUnderlyToken(bytes32 _lendingId) external view returns (address); function borrow( uint256 _pid, bytes32 _lendingId, address _user, uint256 _lendingAmount, uint256 _lendingInterest, uint256 _borrowNumbers ) external; // ether function repayBorrow( bytes32 _lendingId, address _user, uint256 _lendingInterest ) external payable; // erc20 function repayBorrow( bytes32 _lendingId, address _user, uint256 _lendingAmount, uint256 _lendingInterest ) external; function addSupplyPool(address _underlyToken, address _supplyTreasuryFund) external returns (bool); function getBorrowRatePerBlock(uint256 _pid) external view returns (uint256); function getUtilizationRate(uint256 _pid) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "./SupplyTreasuryFundForCompound.sol"; import "./ISupplyBooster.sol"; interface ISupplyRewardFactoryExtra is ISupplyRewardFactory { function addOwner(address _newOwner) external; } contract SupplyPoolManager { address public supplyBooster; address public supplyRewardFactory; address public compoundComptroller; address public owner; address public governance; event SetOwner(address owner); event SetGovernance(address governance); modifier onlyOwner() { require( owner == msg.sender, "SupplyPoolManager: caller is not the owner" ); _; } modifier onlyGovernance() { require( governance == msg.sender, "SupplyPoolManager: caller is not the governance" ); _; } constructor( address _owner, address _supplyBooster, address _supplyRewardFactory, address _compoundComptroller ) public { owner = _owner; governance = _owner; supplyBooster = _supplyBooster; supplyRewardFactory = _supplyRewardFactory; compoundComptroller = _compoundComptroller; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } function setGovernance(address _governance) public onlyOwner { governance = _governance; emit SetGovernance(_governance); } function addSupplyPool(address _compoundCToken) public onlyGovernance { SupplyTreasuryFundForCompound supplyTreasuryFund = new SupplyTreasuryFundForCompound( supplyBooster, _compoundCToken, compoundComptroller, supplyRewardFactory ); address underlyToken; // 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5 = cEther if (_compoundCToken == 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5) { underlyToken = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } else { underlyToken = ICompoundCErc20(_compoundCToken).underlying(); } ISupplyRewardFactoryExtra(supplyRewardFactory).addOwner( address(supplyTreasuryFund) ); ISupplyBooster(supplyBooster).addSupplyPool( underlyToken, address(supplyTreasuryFund) ); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/IBaseReward.sol"; interface ICompoundComptroller { /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function getAssetsIn(address account) external view returns (address[] memory); function checkMembership(address account, address cToken) external view returns (bool); function claimComp(address holder) external; function claimComp(address holder, address[] memory cTokens) external; function getCompAddress() external view returns (address); function getAllMarkets() external view returns (address[] memory); function accountAssets(address user) external view returns (address[] memory); function markets(address _cToken) external view returns (bool isListed, uint256 collateralFactorMantissa); } interface ICompound { function borrow(uint256 borrowAmount) external returns (uint256); function isCToken(address) external view returns (bool); function comptroller() external view returns (ICompoundComptroller); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function balanceOf(address owner) external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function accrualBlockNumber() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function borrowBalanceStored(address user) external view returns (uint256); function exchangeRateStored() external view returns (uint256); function decimals() external view returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function interestRateModel() external view returns (address); } interface ICompoundCEther is ICompound { function repayBorrow() external payable; function mint() external payable; } interface ICompoundCErc20 is ICompound { function repayBorrow(uint256 repayAmount) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function underlying() external returns (address); // like usdc usdt } interface ISupplyRewardFactory { function createReward( address _rewardToken, address _virtualBalance, address _owner ) external returns (address); } contract SupplyTreasuryFundForCompound is ReentrancyGuard { using Address for address payable; using SafeMath for uint256; using SafeERC20 for IERC20; address public rewardCompPool; address public supplyRewardFactory; address public virtualBalance; address public compAddress; address public compoundComptroller; address public underlyToken; address public lpToken; address public owner; uint256 public totalUnderlyToken; uint256 public frozenUnderlyToken; bool public isErc20; bool private initialized; modifier onlyInitialized() { require(initialized, "!initialized"); _; } modifier onlyOwner() { require( msg.sender == owner, "SupplyTreasuryFundForCompound: !authorized" ); _; } constructor( address _owner, address _lpToken, address _compoundComptroller, address _supplyRewardFactory ) public { owner = _owner; compoundComptroller = _compoundComptroller; lpToken = _lpToken; supplyRewardFactory = _supplyRewardFactory; } // call by Owner (SupplyBooster) function initialize( address _virtualBalance, address _underlyToken, bool _isErc20 ) public onlyOwner { require(!initialized, "initialized"); compAddress = ICompoundComptroller(compoundComptroller).getCompAddress(); underlyToken = _underlyToken; virtualBalance = _virtualBalance; isErc20 = _isErc20; rewardCompPool = ISupplyRewardFactory(supplyRewardFactory).createReward( compAddress, virtualBalance, address(this) ); initialized = true; } function _mintEther(uint256 _amount) internal { ICompoundCEther(lpToken).mint{value: _amount}(); } function _mintErc20(uint256 _amount) internal { ICompoundCErc20(lpToken).mint(_amount); } receive() external payable {} function migrate(address _newTreasuryFund, bool _setReward) external onlyOwner nonReentrant returns (uint256) { uint256 cTokens = IERC20(lpToken).balanceOf(address(this)); uint256 redeemState = ICompound(lpToken).redeem(cTokens); require( redeemState == 0, "SupplyTreasuryFundForCompound: !redeemState" ); uint256 bal; if (isErc20) { bal = IERC20(underlyToken).balanceOf(address(this)); IERC20(underlyToken).safeTransfer(owner, bal); } else { bal = address(this).balance; if (bal > 0) { payable(owner).sendValue(bal); } } if (_setReward) { IBaseReward(rewardCompPool).addOwner(_newTreasuryFund); IBaseReward(rewardCompPool).removeOwner(address(this)); } return bal; } function _depositFor(address _for, uint256 _amount) internal { totalUnderlyToken = totalUnderlyToken.add(_amount); if (isErc20) { IERC20(underlyToken).safeApprove(lpToken, 0); IERC20(underlyToken).safeApprove(lpToken, _amount); _mintErc20(_amount); } else { _mintEther(_amount); } if (_for != address(0)) { IBaseReward(rewardCompPool).stake(_for); } } function depositFor(address _for) public payable onlyInitialized onlyOwner nonReentrant { _depositFor(_for, msg.value); } function depositFor(address _for, uint256 _amount) public onlyInitialized onlyOwner nonReentrant { _depositFor(_for, _amount); } function withdrawFor(address _to, uint256 _amount) public onlyInitialized onlyOwner nonReentrant returns (uint256) { IBaseReward(rewardCompPool).withdraw(_to); require( totalUnderlyToken >= _amount, "SupplyTreasuryFundForCompound: !insufficient balance" ); totalUnderlyToken = totalUnderlyToken.sub(_amount); uint256 redeemState = ICompound(lpToken).redeemUnderlying(_amount); require( redeemState == 0, "SupplyTreasuryFundForCompound: !redeemState" ); uint256 bal; if (isErc20) { bal = IERC20(underlyToken).balanceOf(address(this)); IERC20(underlyToken).safeTransfer(_to, bal); } else { bal = address(this).balance; if (bal > 0) { payable(_to).sendValue(bal); } } return bal; } function borrow( address _to, uint256 _lendingAmount, uint256 _lendingInterest ) public onlyInitialized nonReentrant onlyOwner returns (uint256) { totalUnderlyToken = totalUnderlyToken.sub(_lendingAmount); frozenUnderlyToken = frozenUnderlyToken.add(_lendingAmount); uint256 redeemState = ICompound(lpToken).redeemUnderlying( _lendingAmount ); require( redeemState == 0, "SupplyTreasuryFundForCompound: !redeemState" ); if (isErc20) { IERC20(underlyToken).safeTransfer( _to, _lendingAmount.sub(_lendingInterest) ); if (_lendingInterest > 0) { IERC20(underlyToken).safeTransfer(owner, _lendingInterest); } } else { payable(_to).sendValue(_lendingAmount.sub(_lendingInterest)); if (_lendingInterest > 0) { payable(owner).sendValue(_lendingInterest); } } return _lendingInterest; } function repayBorrow() public payable onlyInitialized nonReentrant onlyOwner { _mintEther(msg.value); totalUnderlyToken = totalUnderlyToken.add(msg.value); frozenUnderlyToken = frozenUnderlyToken.sub(msg.value); } function repayBorrow(uint256 _lendingAmount) public onlyInitialized nonReentrant onlyOwner { IERC20(underlyToken).safeApprove(lpToken, 0); IERC20(underlyToken).safeApprove(lpToken, _lendingAmount); _mintErc20(_lendingAmount); totalUnderlyToken = totalUnderlyToken.add(_lendingAmount); frozenUnderlyToken = frozenUnderlyToken.sub(_lendingAmount); } function getBalance() public view returns (uint256) { uint256 exchangeRateStored = ICompound(lpToken).exchangeRateStored(); uint256 cTokens = IERC20(lpToken).balanceOf(address(this)); return exchangeRateStored.mul(cTokens).div(1e18); } function claim() public onlyInitialized onlyOwner nonReentrant returns (uint256) { ICompoundComptroller(compoundComptroller).claimComp(address(this)); uint256 balanceOfComp = IERC20(compAddress).balanceOf(address(this)); if (balanceOfComp > 0) { IERC20(compAddress).safeTransfer(rewardCompPool, balanceOfComp); IBaseReward(rewardCompPool).notifyRewardAmount(balanceOfComp); } uint256 bal; uint256 cTokens = IERC20(lpToken).balanceOf(address(this)); // If Uses withdraws all the money, the remaining ctoken is profit. if (totalUnderlyToken == 0 && frozenUnderlyToken == 0) { if (cTokens > 0) { uint256 redeemState = ICompound(lpToken).redeem(cTokens); require( redeemState == 0, "SupplyTreasuryFundForCompound: !redeemState" ); if (isErc20) { bal = IERC20(underlyToken).balanceOf(address(this)); IERC20(underlyToken).safeTransfer(owner, bal); } else { bal = address(this).balance; if (bal > 0) { payable(owner).sendValue(bal); } } return bal; } } uint256 exchangeRateStored = ICompound(lpToken).exchangeRateCurrent(); // ctoken price uint256 cTokenPrice = cTokens.mul(exchangeRateStored).div(1e18); if (cTokenPrice > totalUnderlyToken.add(frozenUnderlyToken)) { uint256 interestCToken = cTokenPrice .sub(totalUnderlyToken.add(frozenUnderlyToken)) .mul(1e18) .div(exchangeRateStored); uint256 redeemState = ICompound(lpToken).redeem(interestCToken); require( redeemState == 0, "SupplyTreasuryFundForCompound: !redeemState" ); if (isErc20) { bal = IERC20(underlyToken).balanceOf(address(this)); IERC20(underlyToken).safeTransfer(owner, bal); } else { bal = address(this).balance; if (bal > 0) { payable(owner).sendValue(bal); } } } return bal; } function getReward(address _for) public onlyOwner nonReentrant { if (IBaseReward(rewardCompPool).earned(_for) > 0) { IBaseReward(rewardCompPool).getReward(_for); } } function getBorrowRatePerBlock() public view returns (uint256) { return ICompound(lpToken).borrowRatePerBlock(); } /* function getCollateralFactorMantissa() public view returns (uint256) { ICompoundComptroller comptroller = ICompound(lpToken).comptroller(); (bool isListed, uint256 collateralFactorMantissa) = comptroller.markets( lpToken ); return isListed ? collateralFactorMantissa : 800000000000000000; } */ } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./supply/SupplyTreasuryFundForCompound.sol"; import "./convex/IConvexBoosterV2.sol"; import "./supply/ISupplyBooster.sol"; interface ILendingMarket { function addMarketPool( uint256 _convexBoosterPid, uint256[] calldata _supplyBoosterPids, int128[] calldata _curveCoinIds, uint256 _lendingThreshold, uint256 _liquidateThreshold ) external; } interface ISupplyRewardFactoryExtra is ISupplyRewardFactory { function addOwner(address _newOwner) external; } contract GenerateLendingPoolsV2 { address public convexBooster; address public lendingMarket; address public supplyBooster; address public supplyRewardFactory; address public compoundComptroller; address public deployer; constructor(address _deployer) public { deployer = _deployer; } function setLendingContract( address _supplyBooster, address _convexBooster, address _lendingMarket, address _supplyRewardFactory, address _compoundComptroller ) public { require(deployer == msg.sender, "!authorized auth"); supplyBooster = _supplyBooster; convexBooster = _convexBooster; lendingMarket = _lendingMarket; supplyRewardFactory = _supplyRewardFactory; compoundComptroller = _compoundComptroller; } function addConvexBoosterPool(uint256 _originConvexPid) public { require(deployer == msg.sender, "!authorized auth"); require(supplyBooster != address(0), "!supplyBooster"); require(convexBooster != address(0), "!convexBooster"); require(lendingMarket != address(0), "!lendingMarket"); require(supplyRewardFactory != address(0), "!supplyRewardFactory"); IConvexBoosterV2(convexBooster).addConvexPool(_originConvexPid); } function addConvexBoosterPool( uint256 _originConvexPid, address _curveSwapAddress, address _curveZapAddress, address _basePoolAddress, bool _isMeta, bool _isMetaFactory ) public { require(deployer == msg.sender, "!authorized auth"); require(supplyBooster != address(0), "!supplyBooster"); require(convexBooster != address(0), "!convexBooster"); require(lendingMarket != address(0), "!lendingMarket"); require(supplyRewardFactory != address(0), "!supplyRewardFactory"); IConvexBoosterV2(convexBooster).addConvexPool( _originConvexPid, _curveSwapAddress, _curveZapAddress, _basePoolAddress, _isMeta, _isMetaFactory ); } function addLendingMarketPool( uint256 _convexBoosterPid, uint256[] calldata _supplyBoosterPids, int128[] calldata _curveCoinIds ) public { require(deployer == msg.sender, "!authorized auth"); require(supplyBooster != address(0), "!supplyBooster"); require(convexBooster != address(0), "!convexBooster"); require(lendingMarket != address(0), "!lendingMarket"); require(supplyRewardFactory != address(0), "!supplyRewardFactory"); ILendingMarket(lendingMarket).addMarketPool( _convexBoosterPid, _supplyBoosterPids, _curveCoinIds, 100, 50 ); } function addSupplyPoolForCEther(address _compoundCToken) public { _addSupplyPool(_compoundCToken, false); } function addSupplyPoolForCToken(address _compoundCToken) public { _addSupplyPool(_compoundCToken, true); } function _addSupplyPool(address _compoundCToken, bool _isErc20) internal { require(deployer == msg.sender, "!authorized auth"); require(supplyBooster != address(0), "!supplyBooster"); require(convexBooster != address(0), "!convexBooster"); require(lendingMarket != address(0), "!lendingMarket"); require(supplyRewardFactory != address(0), "!supplyRewardFactory"); SupplyTreasuryFundForCompound supplyTreasuryFund = new SupplyTreasuryFundForCompound( supplyBooster, _compoundCToken, compoundComptroller, supplyRewardFactory ); address underlyToken; // 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5 = cEther if (_isErc20) { underlyToken = ICompoundCErc20(_compoundCToken).underlying(); } else { underlyToken = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } ISupplyRewardFactoryExtra(supplyRewardFactory).addOwner( address(supplyTreasuryFund) ); ISupplyBooster(supplyBooster).addSupplyPool( underlyToken, address(supplyTreasuryFund) ); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "./IConvexBooster.sol"; interface IConvexBoosterV2 is IConvexBooster { function liquidate( uint256 _convexPid, int128 _curveCoinId, address _user, uint256 _amount ) external override returns (address, uint256); function depositFor( uint256 _convexPid, uint256 _amount, address _user ) external override returns (bool); function withdrawFor( uint256 _convexPid, uint256 _amount, address _user, bool _freezeTokens ) external override returns (bool); function poolInfo(uint256 _convexPid) external view override returns ( uint256 originConvexPid, address curveSwapAddress, address lpToken, address originCrvRewards, address originStash, address virtualBalance, address rewardCrvPool, address rewardCvxPool, bool shutdown ); function addConvexPool(uint256 _originConvexPid) external override; function addConvexPool(uint256 _originConvexPid, address _curveSwapAddress, address _curveZapAddress, address _basePoolAddress, bool _isMeta, bool _isMetaFactory) external; function getPoolZapAddress(address _lpToken) external view returns (address); function getPoolToken(uint256 _pid) external view returns (address); function calculateTokenAmount( uint256 _pid, uint256 _tokens, int128 _curveCoinId ) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; interface IConvexBooster { function liquidate( uint256 _convexPid, int128 _curveCoinId, address _user, uint256 _amount ) external returns (address, uint256); function depositFor( uint256 _convexPid, uint256 _amount, address _user ) external returns (bool); function withdrawFor( uint256 _convexPid, uint256 _amount, address _user, bool _freezeTokens ) external returns (bool); function poolInfo(uint256 _convexPid) external view returns ( uint256 originConvexPid, address curveSwapAddress, address lpToken, address originCrvRewards, address originStash, address virtualBalance, address rewardCrvPool, address rewardCvxPool, bool shutdown ); function addConvexPool(uint256 _originConvexPid) external; } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./convex/IConvexBoosterV2.sol"; import "./supply/ISupplyBooster.sol"; interface ILendingSponsor { function addSponsor(bytes32 _lendingId, address _user) external payable; function payFee(bytes32 _lendingId, address payable _user) external; } contract LendingMarketV2 is Initializable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public convexBooster; address public supplyBooster; address public lendingSponsor; uint256 public liquidateThresholdBlockNumbers; uint256 public version; address public owner; address public governance; enum UserLendingState { LENDING, EXPIRED, LIQUIDATED } struct PoolInfo { uint256 convexPid; uint256[] supportPids; int128[] curveCoinIds; uint256 lendingThreshold; uint256 liquidateThreshold; uint256 borrowIndex; } struct UserLending { bytes32 lendingId; uint256 token0; uint256 token0Price; uint256 lendingAmount; uint256 borrowAmount; uint256 borrowInterest; uint256 supportPid; int128 curveCoinId; uint256 borrowNumbers; } struct LendingInfo { address user; uint256 pid; uint256 userLendingIndex; uint256 borrowIndex; uint256 startedBlock; uint256 utilizationRate; uint256 supplyRatePerBlock; UserLendingState state; } struct BorrowInfo { uint256 borrowAmount; uint256 supplyAmount; } struct Statistic { uint256 totalCollateral; uint256 totalBorrow; uint256 recentRepayAt; } struct LendingParams { uint256 lendingAmount; uint256 borrowAmount; uint256 borrowInterest; uint256 lendingRate; uint256 utilizationRate; uint256 supplyRatePerBlock; address lpToken; uint256 token0Price; } PoolInfo[] public poolInfo; address public constant ZERO_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 public constant MIN_LIQUIDATE_BLOCK_NUMBERS = 50; uint256 public constant MIN_LENDING_THRESHOLD = 100; uint256 public constant MIN_LIQUIDATE_THRESHOLD = 50; uint256 public constant MAX_LIQUIDATE_BLOCK_NUMBERS = 100; uint256 public constant MAX_LENDING_THRESHOLD = 300; uint256 public constant MAX_LIQUIDATE_THRESHOLD = 300; uint256 public constant SUPPLY_RATE_DENOMINATOR = 1e18; uint256 public constant MAX_LENDFLARE_TOTAL_RATE = 0.5 * 1e18; uint256 public constant THRESHOLD_DENOMINATOR = 1000; uint256 public constant BLOCKS_PER_YEAR = 2102400; // Reference Compound WhitePaperInterestRateModel contract uint256 public constant BLOCKS_PER_DAY = 5760; // user address => container mapping(address => UserLending[]) public userLendings; // lending id => user address mapping(bytes32 => LendingInfo) public lendings; // pool id => (borrowIndex => user lendingId) mapping(uint256 => mapping(uint256 => bytes32)) public poolLending; mapping(bytes32 => BorrowInfo) public borrowInfos; mapping(bytes32 => Statistic) public myStatistics; // number => bool mapping(uint256 => bool) public borrowBlocks; // pid => (user => amount) mapping(uint256 => mapping(address => uint256)) public deposits; event LendingBase( bytes32 indexed lendingId, uint256 marketPid, uint256 supplyPid, int128 curveCoinId, uint256 borrowBlocks ); event Borrow( bytes32 indexed lendingId, address indexed user, uint256 pid, uint256 token0, uint256 token0Price, uint256 lendingAmount, uint256 borrowNumber ); event Initialized(address indexed thisAddress); event RepayBorrow( bytes32 indexed lendingId, address user, UserLendingState state ); event Liquidate( bytes32 indexed lendingId, address user, uint256 liquidateAmount, uint256 gasSpent, UserLendingState state ); event SetOwner(address owner); event SetGovernance(address governance); event SetBorrowBlock(uint256 borrowBlock, bool state); event TogglePausedPool(uint256 pid, bool pause); event PreStored(); event Deposit(address user, uint256 pid, uint256 token0); event Withdraw(address user, uint256 pid, uint256 token0); event SetLiquidateThresholdBlockNumbers(uint256 blockNumbers); event SetLendingThreshold(uint256 pid, uint256 threshold); event SetLiquidateThreshold(uint256 pid, uint256 threshold); event AddMarketPool( uint256 convexBoosterPid, uint256[] supplyBoosterPids, int128[] curveCoinIds, uint256 lendingThreshold, uint256 liquidateThreshold ); modifier onlyOwner() { require(owner == msg.sender, "LendingMarket: caller is not the owner"); _; } modifier onlyGovernance() { require( governance == msg.sender, "LendingMarket: caller is not the governance" ); _; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } /* The default governance user is GenerateLendingPools contract. It will be set to DAO in the future */ function setGovernance(address _governance) public onlyOwner { governance = _governance; emit SetGovernance(_governance); } function initialize( address _owner, address _lendingSponsor, address _convexBooster, address _supplyBooster ) public initializer { owner = _owner; governance = _owner; lendingSponsor = _lendingSponsor; convexBooster = _convexBooster; supplyBooster = _supplyBooster; setBorrowBlock(BLOCKS_PER_DAY * 90, true); setBorrowBlock(BLOCKS_PER_DAY * 180, true); setBorrowBlock(BLOCKS_PER_YEAR, true); liquidateThresholdBlockNumbers = 50; version = 1; emit Initialized(address(this)); } function deposit(uint256 _pid, uint256 _token0) public { require(_pid < poolInfo.length, "!_pid"); PoolInfo storage pool = poolInfo[_pid]; address lpToken = IConvexBoosterV2(convexBooster).getPoolToken( pool.convexPid ); IERC20(lpToken).safeTransferFrom(msg.sender, address(this), _token0); IERC20(lpToken).safeApprove(convexBooster, 0); IERC20(lpToken).safeApprove(convexBooster, _token0); IConvexBooster(convexBooster).depositFor( pool.convexPid, _token0, msg.sender ); deposits[_pid][msg.sender] = deposits[_pid][msg.sender].add(_token0); emit Deposit(msg.sender, _pid, _token0); } function withdraw(uint256 _pid, uint256 _token0) public nonReentrant { require(_pid < poolInfo.length, "!_pid"); PoolInfo storage pool = poolInfo[_pid]; require(deposits[_pid][msg.sender] >= _token0, "!deposits"); deposits[_pid][msg.sender] = deposits[_pid][msg.sender].sub(_token0); IConvexBooster(convexBooster).withdrawFor( pool.convexPid, _token0, msg.sender, false ); emit Withdraw(msg.sender, _pid, _token0); } function borrowForDeposit( uint256 _pid, uint256 _token0, uint256 _borrowBlock, uint256 _supportPid ) public payable nonReentrant { require(borrowBlocks[_borrowBlock], "!borrowBlocks"); require(msg.value == 0.1 ether, "!lendingSponsor"); deposits[_pid][msg.sender] = deposits[_pid][msg.sender].sub(_token0); _borrow(_pid, _supportPid, _borrowBlock, _token0, true); } function borrow( uint256 _pid, uint256 _token0, uint256 _borrowBlock, uint256 _supportPid ) public payable nonReentrant { require(borrowBlocks[_borrowBlock], "!borrowBlocks"); require(msg.value == 0.1 ether, "!lendingSponsor"); _borrow(_pid, _supportPid, _borrowBlock, _token0, false); } function getBorrowInfo( uint256 _convexPid, int128 _curveCoinId, uint256 _token0 ) internal view returns (address, uint256) { address lpToken = IConvexBoosterV2(convexBooster).getPoolToken( _convexPid ); uint256 token0Price = IConvexBoosterV2(convexBooster) .calculateTokenAmount(_convexPid, _token0, _curveCoinId); return (lpToken, token0Price); } function _borrow( uint256 _pid, uint256 _supportPid, uint256 _borrowBlocks, uint256 _token0, bool _preStored ) internal returns (LendingParams memory) { PoolInfo storage pool = poolInfo[_pid]; pool.borrowIndex++; bytes32 lendingId = generateId( msg.sender, _pid, pool.borrowIndex + block.number ); LendingParams memory lendingParams = getLendingInfo( _token0, pool.convexPid, pool.curveCoinIds[_supportPid], pool.supportPids[_supportPid], pool.lendingThreshold, pool.liquidateThreshold, _borrowBlocks ); if (!_preStored) { IERC20(lendingParams.lpToken).safeTransferFrom( msg.sender, address(this), _token0 ); IERC20(lendingParams.lpToken).safeApprove(convexBooster, 0); IERC20(lendingParams.lpToken).safeApprove(convexBooster, _token0); IConvexBooster(convexBooster).depositFor( pool.convexPid, _token0, msg.sender ); } ISupplyBooster(supplyBooster).borrow( pool.supportPids[_supportPid], lendingId, msg.sender, lendingParams.lendingAmount, lendingParams.borrowInterest, _borrowBlocks ); BorrowInfo storage borrowInfo = borrowInfos[ generateId(address(0), _pid, pool.supportPids[_supportPid]) ]; borrowInfo.borrowAmount = borrowInfo.borrowAmount.add( lendingParams.token0Price ); borrowInfo.supplyAmount = borrowInfo.supplyAmount.add( lendingParams.lendingAmount ); Statistic storage statistic = myStatistics[ generateId(msg.sender, _pid, pool.supportPids[_supportPid]) ]; statistic.totalCollateral = statistic.totalCollateral.add(_token0); statistic.totalBorrow = statistic.totalBorrow.add( lendingParams.lendingAmount ); userLendings[msg.sender].push( UserLending({ lendingId: lendingId, token0: _token0, token0Price: lendingParams.token0Price, lendingAmount: lendingParams.lendingAmount, borrowAmount: lendingParams.borrowAmount, borrowInterest: lendingParams.borrowInterest, supportPid: pool.supportPids[_supportPid], curveCoinId: pool.curveCoinIds[_supportPid], borrowNumbers: _borrowBlocks }) ); lendings[lendingId] = LendingInfo({ user: msg.sender, pid: _pid, borrowIndex: pool.borrowIndex, userLendingIndex: userLendings[msg.sender].length - 1, startedBlock: block.number, utilizationRate: lendingParams.utilizationRate, supplyRatePerBlock: lendingParams.supplyRatePerBlock, state: UserLendingState.LENDING }); poolLending[_pid][pool.borrowIndex] = lendingId; ILendingSponsor(lendingSponsor).addSponsor{value: msg.value}( lendingId, msg.sender ); emit LendingBase( lendingId, _pid, pool.supportPids[_supportPid], pool.curveCoinIds[_supportPid], _borrowBlocks ); emit Borrow( lendingId, msg.sender, _pid, _token0, lendingParams.token0Price, lendingParams.lendingAmount, _borrowBlocks ); } function _repayBorrow( bytes32 _lendingId, uint256 _amount, bool _freezeTokens ) internal nonReentrant { LendingInfo storage lendingInfo = lendings[_lendingId]; require(lendingInfo.startedBlock > 0, "!invalid lendingId"); UserLending storage userLending = userLendings[lendingInfo.user][ lendingInfo.userLendingIndex ]; address underlyToken = ISupplyBooster(supplyBooster) .getLendingUnderlyToken(userLending.lendingId); PoolInfo storage pool = poolInfo[lendingInfo.pid]; require( lendingInfo.state == UserLendingState.LENDING, "!UserLendingState" ); require( block.number <= lendingInfo.startedBlock.add(userLending.borrowNumbers), "Expired" ); if (underlyToken == ZERO_ADDRESS) { require( msg.value == _amount && _amount == userLending.lendingAmount, "!_amount" ); ISupplyBooster(supplyBooster).repayBorrow{ value: userLending.lendingAmount }( userLending.lendingId, lendingInfo.user, userLending.borrowInterest ); } else { require( msg.value == 0 && _amount == userLending.lendingAmount, "!_amount" ); IERC20(underlyToken).safeTransferFrom( msg.sender, supplyBooster, userLending.lendingAmount ); ISupplyBooster(supplyBooster).repayBorrow( userLending.lendingId, lendingInfo.user, userLending.lendingAmount, userLending.borrowInterest ); } IConvexBooster(convexBooster).withdrawFor( pool.convexPid, userLending.token0, lendingInfo.user, _freezeTokens ); BorrowInfo storage borrowInfo = borrowInfos[ generateId(address(0), lendingInfo.pid, userLending.supportPid) ]; borrowInfo.borrowAmount = borrowInfo.borrowAmount.sub( userLending.token0Price ); borrowInfo.supplyAmount = borrowInfo.supplyAmount.sub( userLending.lendingAmount ); Statistic storage statistic = myStatistics[ generateId( lendingInfo.user, lendingInfo.pid, userLending.supportPid ) ]; statistic.totalCollateral = statistic.totalCollateral.sub( userLending.token0 ); statistic.totalBorrow = statistic.totalBorrow.sub( userLending.lendingAmount ); statistic.recentRepayAt = block.timestamp; ILendingSponsor(lendingSponsor).payFee( userLending.lendingId, payable(lendingInfo.user) ); lendingInfo.state = UserLendingState.EXPIRED; emit RepayBorrow( userLending.lendingId, lendingInfo.user, lendingInfo.state ); } function repayBorrow(bytes32 _lendingId) public payable { _repayBorrow(_lendingId, msg.value, false); } function repayBorrowERC20(bytes32 _lendingId, uint256 _amount) public { _repayBorrow(_lendingId, _amount, false); } function repayBorrowAndFreezeTokens(bytes32 _lendingId) public payable { _repayBorrow(_lendingId, msg.value, true); } function repayBorrowERC20AndFreezeTokens( bytes32 _lendingId, uint256 _amount ) public { _repayBorrow(_lendingId, _amount, true); } /** @notice Used to liquidate asset @dev If repayment is overdue, it is used to liquidate asset. If valued LP is not enough, can use msg.value or _extraErc20Amount force liquidation @param _lendingId Lending ID @param _extraErc20Amount If liquidate erc-20 asset, fill in extra amount. If native asset, send msg.value */ function liquidate(bytes32 _lendingId, uint256 _extraErc20Amount) public payable nonReentrant { uint256 gasStart = gasleft(); LendingInfo storage lendingInfo = lendings[_lendingId]; require(lendingInfo.startedBlock > 0, "!invalid lendingId"); UserLending storage userLending = userLendings[lendingInfo.user][ lendingInfo.userLendingIndex ]; require( lendingInfo.state == UserLendingState.LENDING, "!UserLendingState" ); require( lendingInfo.startedBlock.add(userLending.borrowNumbers).sub( liquidateThresholdBlockNumbers ) < block.number, "!borrowNumbers" ); PoolInfo storage pool = poolInfo[lendingInfo.pid]; lendingInfo.state = UserLendingState.LIQUIDATED; BorrowInfo storage borrowInfo = borrowInfos[ generateId(address(0), lendingInfo.pid, userLending.supportPid) ]; borrowInfo.borrowAmount = borrowInfo.borrowAmount.sub( userLending.token0Price ); borrowInfo.supplyAmount = borrowInfo.supplyAmount.sub( userLending.lendingAmount ); Statistic storage statistic = myStatistics[ generateId( lendingInfo.user, lendingInfo.pid, userLending.supportPid ) ]; statistic.totalCollateral = statistic.totalCollateral.sub( userLending.token0 ); statistic.totalBorrow = statistic.totalBorrow.sub( userLending.lendingAmount ); (address underlyToken, uint256 liquidateAmount) = IConvexBooster( convexBooster ).liquidate( pool.convexPid, userLending.curveCoinId, lendingInfo.user, userLending.token0 ); if (underlyToken == ZERO_ADDRESS) { liquidateAmount = liquidateAmount.add(msg.value); ISupplyBooster(supplyBooster).liquidate{value: liquidateAmount}( userLending.lendingId, userLending.borrowInterest ); } else { IERC20(underlyToken).safeTransfer(supplyBooster, liquidateAmount); if (_extraErc20Amount > 0) { // Failure without authorization IERC20(underlyToken).safeTransferFrom( msg.sender, supplyBooster, _extraErc20Amount ); } ISupplyBooster(supplyBooster).liquidate( userLending.lendingId, userLending.borrowInterest ); } ILendingSponsor(lendingSponsor).payFee( userLending.lendingId, msg.sender ); uint256 gasSpent = (21000 + gasStart - gasleft()).mul(tx.gasprice); emit Liquidate( userLending.lendingId, lendingInfo.user, liquidateAmount, gasSpent, lendingInfo.state ); } function setLiquidateThresholdBlockNumbers(uint256 _v) public onlyGovernance { require( _v >= MIN_LIQUIDATE_BLOCK_NUMBERS && _v <= MAX_LIQUIDATE_BLOCK_NUMBERS, "!_v" ); liquidateThresholdBlockNumbers = _v; emit SetLiquidateThresholdBlockNumbers(liquidateThresholdBlockNumbers); } function setBorrowBlock(uint256 _number, bool _state) public onlyGovernance { require( _number.sub(liquidateThresholdBlockNumbers) > liquidateThresholdBlockNumbers, "!_number" ); borrowBlocks[_number] = _state; emit SetBorrowBlock(_number, borrowBlocks[_number]); } function setLendingThreshold(uint256 _pid, uint256 _v) public onlyGovernance { require( _v >= MIN_LENDING_THRESHOLD && _v <= MAX_LENDING_THRESHOLD, "!_v" ); PoolInfo storage pool = poolInfo[_pid]; pool.lendingThreshold = _v; emit SetLendingThreshold(_pid, pool.lendingThreshold); } function setLiquidateThreshold(uint256 _pid, uint256 _v) public onlyGovernance { require( _v >= MIN_LIQUIDATE_THRESHOLD && _v <= MAX_LIQUIDATE_THRESHOLD, "!_v" ); PoolInfo storage pool = poolInfo[_pid]; pool.liquidateThreshold = _v; emit SetLiquidateThreshold(_pid, pool.lendingThreshold); } receive() external payable {} /* @param _convexBoosterPid convexBooster contract @param _supplyBoosterPids supply contract @param _curveCoinIds curve coin id of curve COINS */ function addMarketPool( uint256 _convexBoosterPid, uint256[] calldata _supplyBoosterPids, int128[] calldata _curveCoinIds, uint256 _lendingThreshold, uint256 _liquidateThreshold ) public onlyGovernance { require( _lendingThreshold >= MIN_LENDING_THRESHOLD && _lendingThreshold <= MAX_LENDING_THRESHOLD, "!_lendingThreshold" ); require( _liquidateThreshold >= MIN_LIQUIDATE_THRESHOLD && _liquidateThreshold <= MAX_LIQUIDATE_THRESHOLD, "!_liquidateThreshold" ); require( _supplyBoosterPids.length == _curveCoinIds.length, "!_supportPids && _curveCoinIds" ); poolInfo.push( PoolInfo({ convexPid: _convexBoosterPid, supportPids: _supplyBoosterPids, curveCoinIds: _curveCoinIds, lendingThreshold: _lendingThreshold, liquidateThreshold: _liquidateThreshold, borrowIndex: 0 }) ); emit AddMarketPool( _convexBoosterPid, _supplyBoosterPids, _curveCoinIds, _lendingThreshold, _liquidateThreshold ); } /* function toBytes16(uint256 x) internal pure returns (bytes16 b) { return bytes16(bytes32(x)); } */ function generateId( address x, uint256 y, uint256 z ) public pure returns (bytes32) { /* return toBytes16(uint256(keccak256(abi.encodePacked(x, y, z)))); */ return keccak256(abi.encodePacked(x, y, z)); } function poolLength() public view returns (uint256) { return poolInfo.length; } function cursor( uint256 _pid, uint256 _offset, uint256 _size ) public view returns (bytes32[] memory, uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 size = _offset.add(_size) > pool.borrowIndex ? pool.borrowIndex.sub(_offset) : _size; bytes32[] memory userLendingIds = new bytes32[](size); for (uint256 i = 0; i < size; i++) { bytes32 userLendingId = poolLending[_pid][_offset.add(i)]; userLendingIds[i] = userLendingId; } return (userLendingIds, pool.borrowIndex); } function calculateRepayAmount(bytes32 _lendingId) public view returns (uint256) { LendingInfo storage lendingInfo = lendings[_lendingId]; UserLending storage userLending = userLendings[lendingInfo.user][ lendingInfo.userLendingIndex ]; if (lendingInfo.state == UserLendingState.LIQUIDATED) return 0; return userLending.lendingAmount; } function getPoolSupportPids(uint256 _pid) public view returns (uint256[] memory) { PoolInfo storage pool = poolInfo[_pid]; return pool.supportPids; } function getCurveCoinId(uint256 _pid, uint256 _supportPid) public view returns (int128) { PoolInfo storage pool = poolInfo[_pid]; return pool.curveCoinIds[_supportPid]; } function getUserLendingState(bytes32 _lendingId) public view returns (UserLendingState) { LendingInfo storage lendingInfo = lendings[_lendingId]; return lendingInfo.state; } function getLendingInfo( uint256 _token0, uint256 _convexPid, int128 _curveCoinId, uint256 _supplyPid, uint256 _lendingThreshold, uint256 _liquidateThreshold, uint256 _borrowBlocks ) public view returns (LendingParams memory) { (address lpToken, uint256 token0Price) = getBorrowInfo( _convexPid, _curveCoinId, _token0 ); uint256 utilizationRate = ISupplyBooster(supplyBooster) .getUtilizationRate(_supplyPid); uint256 supplyRatePerBlock = ISupplyBooster(supplyBooster) .getBorrowRatePerBlock(_supplyPid); uint256 supplyRate = getSupplyRate(supplyRatePerBlock, _borrowBlocks); uint256 lendflareTotalRate; if (utilizationRate > 0) { lendflareTotalRate = getLendingRate( supplyRate, getAmplificationFactor(utilizationRate) ); } else { lendflareTotalRate = supplyRate.sub(SUPPLY_RATE_DENOMINATOR); } uint256 lendingAmount = token0Price.mul(SUPPLY_RATE_DENOMINATOR); lendingAmount = lendingAmount.mul( THRESHOLD_DENOMINATOR.sub(_lendingThreshold).sub( _liquidateThreshold ) ); lendingAmount = lendingAmount.div(THRESHOLD_DENOMINATOR); uint256 repayBorrowAmount = lendingAmount.div(SUPPLY_RATE_DENOMINATOR); uint256 borrowAmount = lendingAmount.div( SUPPLY_RATE_DENOMINATOR.add(lendflareTotalRate) ); uint256 borrowInterest = repayBorrowAmount.sub(borrowAmount); return LendingParams({ lendingAmount: repayBorrowAmount, borrowAmount: borrowAmount, borrowInterest: borrowInterest, lendingRate: lendflareTotalRate, utilizationRate: utilizationRate, supplyRatePerBlock: supplyRatePerBlock, lpToken: lpToken, token0Price: token0Price }); } function getUserLendingsLength(address _user) public view returns (uint256) { return userLendings[_user].length; } function getSupplyRate(uint256 _supplyBlockRate, uint256 n) public pure returns ( uint256 total // _supplyBlockRate and the result are scaled to 1e18 ) { uint256 term = 1e18; // term0 = xn, term1 = n(n-1)/2! * x^2, term2 = term1 * (n - 2) / (i + 1) * x uint256 result = 1e18; // partial sum of terms uint256 MAX_TERMS = 10; // up to MAX_TERMS are calculated, the error is negligible for (uint256 i = 0; i < MAX_TERMS && i < n; ++i) { term = term.mul(n - i).div(i + 1).mul(_supplyBlockRate).div(1e18); total = total.add(term); } total = total.add(result); } function getAmplificationFactor(uint256 _utilizationRate) public pure returns (uint256) { if (_utilizationRate <= 0.9 * 1e18) { return uint256(10).mul(_utilizationRate).div(9).add(1e18); } return uint256(20).mul(_utilizationRate).sub(16 * 1e18); } // lendflare total rate function getLendingRate(uint256 _supplyRate, uint256 _amplificationFactor) public pure returns (uint256) { return _supplyRate.sub(1e18).mul(_amplificationFactor).div(1e18); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/IVirtualBalanceWrapper.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; interface ILendFlareToken { function futureEpochTimeWrite() external returns (uint256); function rate() external view returns (uint256); } interface IMinter { function minted(address addr, address self) external view returns (uint256); } interface ILendFlareGaugeModel { function getGaugeWeightShare(address addr) external view returns (uint256); } contract LendFlareGauge is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant TOKENLESS_PRODUCTION = 40; uint256 constant BOOST_WARMUP = 2 weeks; uint256 constant WEEK = 1 weeks; address public virtualBalance; uint256 public working_supply; uint256 public period; uint256 public inflation_rate; uint256 public future_epoch_time; address public lendFlareVotingEscrow; address public lendFlareToken; address public lendFlareTokenMinter; address public lendFlareGaugeModel; mapping(uint256 => uint256) public period_timestamp; mapping(uint256 => uint256) public integrate_inv_supply; mapping(address => uint256) public integrate_inv_supply_of; mapping(address => uint256) public integrate_checkpoint_of; mapping(address => uint256) public totalAccrued; mapping(address => uint256) public rewardLiquidityLimits; event UpdateLiquidityLimit( address user, uint256 original_balance, uint256 original_supply, uint256 reward_liquidity_limits, uint256 working_supply ); constructor( address _virtualBalance, address _lendFlareToken, address _lendFlareVotingEscrow, address _lendFlareGaugeModel, address _lendFlareTokenMinter ) public { virtualBalance = _virtualBalance; lendFlareVotingEscrow = _lendFlareVotingEscrow; lendFlareToken = _lendFlareToken; lendFlareTokenMinter = _lendFlareTokenMinter; lendFlareGaugeModel = _lendFlareGaugeModel; } function _updateLiquidityLimit( address addr, uint256 l, uint256 L ) internal { uint256 voting_balance = IERC20(lendFlareVotingEscrow).balanceOf(addr); uint256 voting_total = IERC20(lendFlareVotingEscrow).totalSupply(); uint256 lim = (l * TOKENLESS_PRODUCTION) / 100; if ( voting_total > 0 && block.timestamp > period_timestamp[0] + BOOST_WARMUP ) { lim += (((L * voting_balance) / voting_total) * (100 - TOKENLESS_PRODUCTION)) / 100; } lim = min(l, lim); uint256 old_bal = rewardLiquidityLimits[addr]; rewardLiquidityLimits[addr] = lim; uint256 _working_supply = working_supply + lim - old_bal; working_supply = _working_supply; emit UpdateLiquidityLimit(addr, l, L, lim, _working_supply); } function _checkpoint(address addr) internal { uint256 _period_time = period_timestamp[period]; uint256 _integrate_inv_supply = integrate_inv_supply[period]; uint256 rate = inflation_rate; uint256 new_rate = rate; uint256 prev_future_epoch = future_epoch_time; if (prev_future_epoch >= _period_time) { future_epoch_time = ILendFlareToken(lendFlareToken) .futureEpochTimeWrite(); new_rate = ILendFlareToken(lendFlareToken).rate(); require(new_rate > 0, "!new_rate"); inflation_rate = new_rate; } uint256 _reward_liquidity_limits = rewardLiquidityLimits[addr]; uint256 _working_supply = working_supply; if (block.timestamp > _period_time) { uint256 prev_week_time = _period_time; uint256 week_time = min( ((_period_time + WEEK) / WEEK) * WEEK, block.timestamp ); for (uint256 i = 0; i < 500; i++) { uint256 dt = week_time - prev_week_time; uint256 w = ILendFlareGaugeModel(lendFlareGaugeModel) .getGaugeWeightShare(address(this)); if (_working_supply > 0) { if ( prev_future_epoch >= prev_week_time && prev_future_epoch < week_time ) { _integrate_inv_supply += (rate * w * (prev_future_epoch - prev_week_time)) / _working_supply; rate = new_rate; _integrate_inv_supply += (rate * w * (week_time - prev_future_epoch)) / _working_supply; } else { _integrate_inv_supply += (rate * w * dt) / _working_supply; } if (week_time == block.timestamp) break; prev_week_time = week_time; week_time = min(week_time + WEEK, block.timestamp); } } } period += 1; period_timestamp[period] = block.timestamp; integrate_inv_supply[period] = _integrate_inv_supply; totalAccrued[addr] += (_reward_liquidity_limits * (_integrate_inv_supply - integrate_inv_supply_of[addr])) / 10**18; integrate_inv_supply_of[addr] = _integrate_inv_supply; integrate_checkpoint_of[addr] = block.timestamp; } function updateReward(address addr) public nonReentrant returns (bool) { _checkpoint(addr); _updateLiquidityLimit( addr, IVirtualBalanceWrapper(virtualBalance).balanceOf(addr), IVirtualBalanceWrapper(virtualBalance).totalSupply() ); return true; } function claimableTokens(address addr) public nonReentrant returns (uint256) { _checkpoint(addr); return totalAccrued[addr] - IMinter(lendFlareTokenMinter).minted(addr, address(this)); } function lastCheckpointTimestamp() public view returns (uint256) { return period_timestamp[period]; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract SupplyPoolGaugeFactory { address public owner; event CreateGauge(address gauge); constructor() public { owner = msg.sender; } function setOwner(address _owner) external { require( msg.sender == owner, "SupplyPoolGaugeFactory: !authorized setOwner" ); owner = _owner; } function createGauge( address _virtualBalance, address _lendflareToken, address _lendflareVotingEscrow, address _lendflareGaugeModel, address _lendflareTokenMinter ) public returns (address) { require( msg.sender == owner, "SupplyPoolGaugeFactory: !authorized createGauge" ); LendFlareGauge gauge = new LendFlareGauge( _virtualBalance, _lendflareToken, _lendflareVotingEscrow, _lendflareGaugeModel, _lendflareTokenMinter ); emit CreateGauge(address(gauge)); return address(gauge); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "../common/IVirtualBalanceWrapper.sol"; import "../common/IBaseReward.sol"; import "./ISupplyBooster.sol"; interface ILendFlareGauge { function updateReward(address addr) external returns (bool); } interface ILendFlareMinter { function mintFor(address gauge_addr, address _for) external; } interface ILendflareToken { function minter() external view returns (address); } interface ILendFlareVotingEscrow { function addRewardPool(address _v) external returns (bool); } interface ISupplyPoolGaugeFactory { function createGauge( address _virtualBalance, address _lendflareToken, address _lendflareVotingEscrow, address _lendflareGaugeModel, address _lendflareTokenMinter ) external returns (address); } interface ILendflareGaugeModel { function addGauge(address _gauge, uint256 _weight) external; function toggleGauge(address _gauge, bool _state) external; } interface ISupplyRewardFactory { function createReward( address _rewardToken, address _virtualBalance, address _owner ) external returns (address); } contract SupplyPoolExtraRewardFactory is ReentrancyGuard, Initializable { using Address for address payable; using SafeERC20 for IERC20; address public owner; address public supplyBooster; address public supplyRewardFactory; address public supplyPoolGaugeFactory; address public lendflareVotingEscrow; address public lendflareToken; address public lendflareGaugeModel; mapping(uint256 => address) public veLendFlarePool; // pid => extra rewards mapping(uint256 => address) public gaugePool; // pid => extra rewards // @custom:oz-upgrades-unsafe-allow constructor constructor() public initializer {} function initialize( address _supplyBooster, address _supplyRewardFactory, address _supplyPoolGaugeFactory, address _lendflareGaugeModel, address _lendflareVotingEscrow, address _lendflareToken, address _owner ) public initializer { owner = _owner; supplyBooster = _supplyBooster; supplyRewardFactory = _supplyRewardFactory; supplyPoolGaugeFactory = _supplyPoolGaugeFactory; lendflareVotingEscrow = _lendflareVotingEscrow; lendflareToken = _lendflareToken; lendflareGaugeModel = _lendflareGaugeModel; } function setOwner(address _owner) external { require( msg.sender == owner, "SupplyPoolExtraRewardFactory: !authorized setOwner" ); owner = _owner; } function createPool( uint256 _pid, address _underlyToken, address _virtualBalance, bool _isErc20 ) internal { address lendflareMinter = ILendflareToken(lendflareToken).minter(); require(lendflareMinter != address(0), "!lendflareMinter"); address poolGauge = ISupplyPoolGaugeFactory(supplyPoolGaugeFactory) .createGauge( _virtualBalance, lendflareToken, lendflareVotingEscrow, lendflareGaugeModel, lendflareMinter ); // default weight = 100 * 1e18 ILendflareGaugeModel(lendflareGaugeModel).addGauge(poolGauge, 100e18); address rewardVeLendFlarePool; if (_isErc20) { rewardVeLendFlarePool = ISupplyRewardFactory(supplyRewardFactory) .createReward( _underlyToken, lendflareVotingEscrow, address(this) ); } else { rewardVeLendFlarePool = ISupplyRewardFactory(supplyRewardFactory) .createReward(address(0), lendflareVotingEscrow, address(this)); } ILendFlareVotingEscrow(lendflareVotingEscrow).addRewardPool( rewardVeLendFlarePool ); IBaseReward(rewardVeLendFlarePool).addOwner(lendflareVotingEscrow); veLendFlarePool[_pid] = rewardVeLendFlarePool; gaugePool[_pid] = poolGauge; } function updateOldPool(uint256 _pid) public { require( msg.sender == owner, "SupplyPoolExtraRewardFactory: !authorized updateOldPool" ); require(veLendFlarePool[_pid] == address(0), "!veLendFlarePool"); require(gaugePool[_pid] == address(0), "!gaugePool"); ( address underlyToken, , , address virtualBalance, bool isErc20, ) = ISupplyBooster(supplyBooster).poolInfo(_pid); createPool(_pid, underlyToken, virtualBalance, isErc20); } function addExtraReward( uint256 _pid, address _lpToken, address _virtualBalance, bool _isErc20 ) public { require( msg.sender == supplyBooster, "SupplyPoolExtraRewardFactory: !authorized addExtraReward" ); createPool(_pid, _lpToken, _virtualBalance, _isErc20); } function toggleShutdownPool(uint256 _pid, bool _state) public { require( msg.sender == supplyBooster, "SupplyPoolExtraRewardFactory: !authorized toggleShutdownPool" ); ILendflareGaugeModel(lendflareGaugeModel).toggleGauge( gaugePool[_pid], _state ); } function getRewards(uint256 _pid, address _for) public nonReentrant { require( msg.sender == supplyBooster, "SupplyPoolExtraRewardFactory: !authorized getRewards" ); address lendflareMinter = ILendflareToken(lendflareToken).minter(); if (lendflareMinter != address(0)) { ILendFlareMinter(lendflareMinter).mintFor(gaugePool[_pid], _for); } } function beforeStake(uint256 _pid, address _for) public nonReentrant {} function afterStake(uint256 _pid, address _for) public nonReentrant { require( msg.sender == supplyBooster, "SupplyPoolExtraRewardFactory: !authorized afterStake" ); ILendFlareGauge(gaugePool[_pid]).updateReward(_for); } function beforeWithdraw(uint256 _pid, address _for) public nonReentrant {} function afterWithdraw(uint256 _pid, address _for) public nonReentrant { require( msg.sender == supplyBooster, "SupplyPoolExtraRewardFactory: !authorized afterWithdraw" ); ILendFlareGauge(gaugePool[_pid]).updateReward(_for); } function getVeLFTUserRewards(uint256[] memory _pids) public nonReentrant { for (uint256 i = 0; i < _pids.length; i++) { if (IBaseReward(veLendFlarePool[_pids[i]]).earned(msg.sender) > 0) { IBaseReward(veLendFlarePool[_pids[i]]).getReward(msg.sender); } } } function notifyRewardAmount( uint256 _pid, address _underlyToken, uint256 _amount ) public payable nonReentrant { require( msg.sender == supplyBooster, "SupplyPoolExtraRewardFactory: !authorized notifyRewardAmount" ); if (_underlyToken == address(0)) { payable(veLendFlarePool[_pid]).sendValue(_amount); } else { IERC20(_underlyToken).safeTransfer(veLendFlarePool[_pid], _amount); } IBaseReward(veLendFlarePool[_pid]).notifyRewardAmount(_amount); } receive() external payable {} } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "./common/IBaseReward.sol"; // Reference @openzeppelin/contracts/token/ERC20/IERC20.sol interface ILendFlareVotingEscrow { /** * @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); } contract LendFlareVotingEscrow is Initializable, ReentrancyGuard, ILendFlareVotingEscrow { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 constant WEEK = 1 weeks; // all future times are rounded by week uint256 constant MAXTIME = 4 * 365 * 86400; // 4 years string constant NAME = "Vote-escrowed LFT"; string constant SYMBOL = "VeLFT"; uint8 constant DECIMALS = 18; address public token; address public rewardManager; uint256 public override totalSupply; enum DepositTypes { DEPOSIT_FOR_TYPE, CREATE_LOCK_TYPE, INCREASE_LOCK_AMOUNT, INCREASE_UNLOCK_TIME } struct Point { uint256 bias; uint256 slope; // dweight / dt uint256 ts; // timestamp } struct LockedBalance { uint256 amount; uint256 end; } IBaseReward[] public rewardPools; mapping(address => LockedBalance) public lockedBalances; mapping(address => mapping(uint256 => Point)) public userPointHistory; // user => ( user epoch => point ) mapping(address => uint256) public userPointEpoch; // user => user epoch event Deposit( address indexed provider, uint256 value, uint256 indexed locktime, DepositTypes depositTypes, uint256 ts ); event Withdraw(address indexed provider, uint256 value, uint256 ts); event TotalSupply(uint256 prevSupply, uint256 supply); // @custom:oz-upgrades-unsafe-allow constructor constructor() public initializer {} function initialize(address _token, address _rewardManager) public initializer { token = _token; rewardManager = _rewardManager; } modifier onlyRewardManager() { require( rewardManager == msg.sender, "LendFlareVotingEscrow: caller is not the rewardManager" ); _; } function rewardPoolsLength() external view returns (uint256) { return rewardPools.length; } function addRewardPool(address _v) external onlyRewardManager returns (bool) { require(_v != address(0), "!_v"); rewardPools.push(IBaseReward(_v)); return true; } function clearRewardPools() external onlyRewardManager { delete rewardPools; } function _checkpoint(address _sender, LockedBalance storage _newLocked) internal { Point storage point = userPointHistory[_sender][ ++userPointEpoch[_sender] ]; point.ts = block.timestamp; if (_newLocked.end > block.timestamp) { point.slope = _newLocked.amount.div(MAXTIME); point.bias = point.slope.mul(_newLocked.end.sub(block.timestamp)); } } function _depositFor( address _sender, uint256 _amount, uint256 _unlockTime, LockedBalance storage _locked, DepositTypes _depositTypes ) internal { uint256 oldTotalSupply = totalSupply; if (_amount > 0) { IERC20(token).safeTransferFrom(_sender, address(this), _amount); } _locked.amount = _locked.amount.add(_amount); totalSupply = totalSupply.add(_amount); if (_unlockTime > 0) { _locked.end = _unlockTime; } for (uint256 i = 0; i < rewardPools.length; i++) { rewardPools[i].stake(_sender); } _checkpoint(_sender, _locked); emit Deposit( _sender, _amount, _locked.end, _depositTypes, block.timestamp ); emit TotalSupply(oldTotalSupply, totalSupply); } function deposit(uint256 _amount) external nonReentrant { LockedBalance storage locked = lockedBalances[msg.sender]; require(_amount > 0, "need non-zero value"); require(locked.amount > 0, "no existing lock found"); require( locked.end > block.timestamp, "cannot add to expired lock. Withdraw" ); _depositFor( msg.sender, _amount, 0, locked, DepositTypes.DEPOSIT_FOR_TYPE ); } function createLock(uint256 _amount, uint256 _unlockTime) external nonReentrant { LockedBalance storage locked = lockedBalances[msg.sender]; uint256 availableTime = formatWeekTs(_unlockTime); require(_amount > 0, "need non-zero value"); require(locked.amount == 0, "Withdraw old tokens first"); require( availableTime > block.timestamp, "can only lock until time in the future" ); require( availableTime <= block.timestamp + MAXTIME, "voting lock can be 4 years max" ); _depositFor( msg.sender, _amount, availableTime, locked, DepositTypes.CREATE_LOCK_TYPE ); } function increaseAmount(uint256 _amount) external nonReentrant { LockedBalance storage locked = lockedBalances[msg.sender]; require(_amount > 0, "need non-zero value"); require(locked.amount > 0, "No existing lock found"); require( locked.end > block.timestamp, "Cannot add to expired lock. Withdraw" ); _depositFor( msg.sender, _amount, 0, locked, DepositTypes.INCREASE_LOCK_AMOUNT ); } function increaseUnlockTime(uint256 _unlockTime) external nonReentrant { LockedBalance storage locked = lockedBalances[msg.sender]; uint256 availableTime = formatWeekTs(_unlockTime); require(locked.end > block.timestamp, "Lock expired"); require(locked.amount > 0, "Nothing is locked"); require(availableTime > locked.end, "Can only increase lock duration"); require( availableTime <= block.timestamp + MAXTIME, "Voting lock can be 4 years max" ); _depositFor( msg.sender, 0, availableTime, locked, DepositTypes.INCREASE_UNLOCK_TIME ); } function withdraw() public nonReentrant { LockedBalance storage locked = lockedBalances[msg.sender]; require(block.timestamp >= locked.end, "The lock didn't expire"); uint256 oldTotalSupply = totalSupply; uint256 lockedAmount = locked.amount; totalSupply = totalSupply.sub(lockedAmount); locked.amount = 0; locked.end = 0; _checkpoint(msg.sender, locked); IERC20(token).safeTransfer(msg.sender, lockedAmount); for (uint256 i = 0; i < rewardPools.length; i++) { rewardPools[i].withdraw(msg.sender); } emit Withdraw(msg.sender, lockedAmount, block.timestamp); emit TotalSupply(oldTotalSupply, totalSupply); } function formatWeekTs(uint256 _unixTime) public pure returns (uint256) { return _unixTime.div(WEEK).mul(WEEK); } function balanceOf(address _sender) external view override returns (uint256) { uint256 userEpoch = userPointEpoch[_sender]; if (userEpoch == 0) return 0; Point storage point = userPointHistory[_sender][userEpoch]; return point.bias.sub(point.slope.mul(block.timestamp.sub(point.ts))); } function name() public pure returns (string memory) { return NAME; } function symbol() public pure returns (string memory) { return SYMBOL; } function decimals() public pure returns (uint8) { return DECIMALS; } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./convex/IConvexBooster.sol"; import "./supply/ISupplyBooster.sol"; interface ICurveSwap { function calc_withdraw_one_coin(uint256 _tokenAmount, int128 _tokenId) external view returns (uint256); } interface ILendingSponsor { function addSponsor(bytes32 _lendingId, address _user) external payable; function payFee(bytes32 _lendingId, address payable _user) external; } contract LendingMarket is Initializable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public convexBooster; address public supplyBooster; address public lendingSponsor; uint256 public liquidateThresholdBlockNumbers; uint256 public version; address public owner; address public governance; enum UserLendingState { LENDING, EXPIRED, LIQUIDATED } struct PoolInfo { uint256 convexPid; uint256[] supportPids; int128[] curveCoinIds; uint256 lendingThreshold; uint256 liquidateThreshold; uint256 borrowIndex; } struct UserLending { bytes32 lendingId; uint256 token0; uint256 token0Price; uint256 lendingAmount; uint256 borrowAmount; uint256 borrowInterest; uint256 supportPid; int128 curveCoinId; uint256 borrowNumbers; } struct LendingInfo { address user; uint256 pid; uint256 userLendingIndex; uint256 borrowIndex; uint256 startedBlock; uint256 utilizationRate; uint256 supplyRatePerBlock; UserLendingState state; } struct BorrowInfo { uint256 borrowAmount; uint256 supplyAmount; } struct Statistic { uint256 totalCollateral; uint256 totalBorrow; uint256 recentRepayAt; } struct LendingParams { uint256 lendingAmount; uint256 borrowAmount; uint256 borrowInterest; uint256 lendingRate; uint256 utilizationRate; uint256 supplyRatePerBlock; address lpToken; uint256 token0Price; } PoolInfo[] public poolInfo; address public constant ZERO_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 public constant MIN_LIQUIDATE_BLOCK_NUMBERS = 50; uint256 public constant MIN_LENDING_THRESHOLD = 100; uint256 public constant MIN_LIQUIDATE_THRESHOLD = 50; uint256 public constant MAX_LIQUIDATE_BLOCK_NUMBERS = 100; uint256 public constant MAX_LENDING_THRESHOLD = 300; uint256 public constant MAX_LIQUIDATE_THRESHOLD = 300; uint256 public constant SUPPLY_RATE_DENOMINATOR = 1e18; uint256 public constant MAX_LENDFLARE_TOTAL_RATE = 0.5 * 1e18; uint256 public constant THRESHOLD_DENOMINATOR = 1000; uint256 public constant BLOCKS_PER_YEAR = 2102400; // Reference Compound WhitePaperInterestRateModel contract uint256 public constant BLOCKS_PER_DAY = 5760; // user address => container mapping(address => UserLending[]) public userLendings; // lending id => user address mapping(bytes32 => LendingInfo) public lendings; // pool id => (borrowIndex => user lendingId) mapping(uint256 => mapping(uint256 => bytes32)) public poolLending; mapping(bytes32 => BorrowInfo) public borrowInfos; mapping(bytes32 => Statistic) public myStatistics; // number => bool mapping(uint256 => bool) public borrowBlocks; event LendingBase( bytes32 indexed lendingId, uint256 marketPid, uint256 supplyPid, int128 curveCoinId, uint256 borrowBlocks ); event Borrow( bytes32 indexed lendingId, address indexed user, uint256 pid, uint256 token0, uint256 token0Price, uint256 lendingAmount, uint256 borrowNumber ); event Initialized(address indexed thisAddress); event RepayBorrow( bytes32 indexed lendingId, address user, UserLendingState state ); event Liquidate( bytes32 indexed lendingId, address user, uint256 liquidateAmount, uint256 gasSpent, UserLendingState state ); event SetOwner(address owner); event SetGovernance(address governance); event SetBorrowBlock(uint256 borrowBlock, bool state); modifier onlyOwner() { require(owner == msg.sender, "LendingMarket: caller is not the owner"); _; } modifier onlyGovernance() { require( governance == msg.sender, "LendingMarket: caller is not the governance" ); _; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } /* The default governance user is GenerateLendingPools contract. It will be set to DAO in the future */ function setGovernance(address _governance) public onlyOwner { governance = _governance; emit SetGovernance(_governance); } function initialize( address _owner, address _lendingSponsor, address _convexBooster, address _supplyBooster ) public initializer { owner = _owner; governance = _owner; lendingSponsor = _lendingSponsor; convexBooster = _convexBooster; supplyBooster = _supplyBooster; setBorrowBlock(BLOCKS_PER_DAY * 90, true); setBorrowBlock(BLOCKS_PER_DAY * 180, true); setBorrowBlock(BLOCKS_PER_YEAR, true); liquidateThresholdBlockNumbers = 50; version = 1; emit Initialized(address(this)); } function borrow( uint256 _pid, uint256 _token0, uint256 _borrowBlock, uint256 _supportPid ) public payable nonReentrant { require(borrowBlocks[_borrowBlock], "!borrowBlocks"); require(msg.value == 0.1 ether, "!lendingSponsor"); _borrow(_pid, _supportPid, _borrowBlock, _token0); } function _getCurveInfo( uint256 _convexPid, int128 _curveCoinId, uint256 _token0 ) internal view returns (address lpToken, uint256 token0Price) { address curveSwapAddress; (, curveSwapAddress, lpToken, , , , , , ) = IConvexBooster( convexBooster ).poolInfo(_convexPid); token0Price = ICurveSwap(curveSwapAddress).calc_withdraw_one_coin( _token0, _curveCoinId ); } function _borrow( uint256 _pid, uint256 _supportPid, uint256 _borrowBlocks, uint256 _token0 ) internal returns (LendingParams memory) { PoolInfo storage pool = poolInfo[_pid]; pool.borrowIndex++; bytes32 lendingId = generateId( msg.sender, _pid, pool.borrowIndex + block.number ); LendingParams memory lendingParams = getLendingInfo( _token0, pool.convexPid, pool.curveCoinIds[_supportPid], pool.supportPids[_supportPid], pool.lendingThreshold, pool.liquidateThreshold, _borrowBlocks ); IERC20(lendingParams.lpToken).safeTransferFrom( msg.sender, address(this), _token0 ); IERC20(lendingParams.lpToken).safeApprove(convexBooster, 0); IERC20(lendingParams.lpToken).safeApprove(convexBooster, _token0); ISupplyBooster(supplyBooster).borrow( pool.supportPids[_supportPid], lendingId, msg.sender, lendingParams.lendingAmount, lendingParams.borrowInterest, _borrowBlocks ); IConvexBooster(convexBooster).depositFor( pool.convexPid, _token0, msg.sender ); BorrowInfo storage borrowInfo = borrowInfos[ generateId(address(0), _pid, pool.supportPids[_supportPid]) ]; borrowInfo.borrowAmount = borrowInfo.borrowAmount.add( lendingParams.token0Price ); borrowInfo.supplyAmount = borrowInfo.supplyAmount.add( lendingParams.lendingAmount ); Statistic storage statistic = myStatistics[ generateId(msg.sender, _pid, pool.supportPids[_supportPid]) ]; statistic.totalCollateral = statistic.totalCollateral.add(_token0); statistic.totalBorrow = statistic.totalBorrow.add( lendingParams.lendingAmount ); userLendings[msg.sender].push( UserLending({ lendingId: lendingId, token0: _token0, token0Price: lendingParams.token0Price, lendingAmount: lendingParams.lendingAmount, borrowAmount: lendingParams.borrowAmount, borrowInterest: lendingParams.borrowInterest, supportPid: pool.supportPids[_supportPid], curveCoinId: pool.curveCoinIds[_supportPid], borrowNumbers: _borrowBlocks }) ); lendings[lendingId] = LendingInfo({ user: msg.sender, pid: _pid, borrowIndex: pool.borrowIndex, userLendingIndex: userLendings[msg.sender].length - 1, startedBlock: block.number, utilizationRate: lendingParams.utilizationRate, supplyRatePerBlock: lendingParams.supplyRatePerBlock, state: UserLendingState.LENDING }); poolLending[_pid][pool.borrowIndex] = lendingId; ILendingSponsor(lendingSponsor).addSponsor{value: msg.value}( lendingId, msg.sender ); emit LendingBase( lendingId, _pid, pool.supportPids[_supportPid], pool.curveCoinIds[_supportPid], _borrowBlocks ); emit Borrow( lendingId, msg.sender, _pid, _token0, lendingParams.token0Price, lendingParams.lendingAmount, _borrowBlocks ); } function _repayBorrow( bytes32 _lendingId, uint256 _amount, bool _freezeTokens ) internal nonReentrant { LendingInfo storage lendingInfo = lendings[_lendingId]; require(lendingInfo.startedBlock > 0, "!invalid lendingId"); UserLending storage userLending = userLendings[lendingInfo.user][ lendingInfo.userLendingIndex ]; address underlyToken = ISupplyBooster(supplyBooster) .getLendingUnderlyToken(userLending.lendingId); PoolInfo storage pool = poolInfo[lendingInfo.pid]; require( lendingInfo.state == UserLendingState.LENDING, "!UserLendingState" ); require( block.number <= lendingInfo.startedBlock.add(userLending.borrowNumbers), "Expired" ); if (underlyToken == ZERO_ADDRESS) { require( msg.value == _amount && _amount == userLending.lendingAmount, "!_amount" ); ISupplyBooster(supplyBooster).repayBorrow{ value: userLending.lendingAmount }( userLending.lendingId, lendingInfo.user, userLending.borrowInterest ); } else { require( msg.value == 0 && _amount == userLending.lendingAmount, "!_amount" ); IERC20(underlyToken).safeTransferFrom( msg.sender, supplyBooster, userLending.lendingAmount ); ISupplyBooster(supplyBooster).repayBorrow( userLending.lendingId, lendingInfo.user, userLending.lendingAmount, userLending.borrowInterest ); } IConvexBooster(convexBooster).withdrawFor( pool.convexPid, userLending.token0, lendingInfo.user, _freezeTokens ); BorrowInfo storage borrowInfo = borrowInfos[ generateId(address(0), lendingInfo.pid, userLending.supportPid) ]; borrowInfo.borrowAmount = borrowInfo.borrowAmount.sub( userLending.token0Price ); borrowInfo.supplyAmount = borrowInfo.supplyAmount.sub( userLending.lendingAmount ); Statistic storage statistic = myStatistics[ generateId( lendingInfo.user, lendingInfo.pid, userLending.supportPid ) ]; statistic.totalCollateral = statistic.totalCollateral.sub( userLending.token0 ); statistic.totalBorrow = statistic.totalBorrow.sub( userLending.lendingAmount ); statistic.recentRepayAt = block.timestamp; ILendingSponsor(lendingSponsor).payFee( userLending.lendingId, payable(lendingInfo.user) ); lendingInfo.state = UserLendingState.EXPIRED; emit RepayBorrow( userLending.lendingId, lendingInfo.user, lendingInfo.state ); } function repayBorrow(bytes32 _lendingId) public payable { _repayBorrow(_lendingId, msg.value, false); } function repayBorrowERC20(bytes32 _lendingId, uint256 _amount) public { _repayBorrow(_lendingId, _amount, false); } function repayBorrowAndFreezeTokens(bytes32 _lendingId) public payable { _repayBorrow(_lendingId, msg.value, true); } function repayBorrowERC20AndFreezeTokens( bytes32 _lendingId, uint256 _amount ) public { _repayBorrow(_lendingId, _amount, true); } /** @notice Used to liquidate asset @dev If repayment is overdue, it is used to liquidate asset. If valued LP is not enough, can use msg.value or _extraErc20Amount force liquidation @param _lendingId Lending ID @param _extraErc20Amount If liquidate erc-20 asset, fill in extra amount. If native asset, send msg.value */ function liquidate(bytes32 _lendingId, uint256 _extraErc20Amount) public payable nonReentrant { uint256 gasStart = gasleft(); LendingInfo storage lendingInfo = lendings[_lendingId]; require(lendingInfo.startedBlock > 0, "!invalid lendingId"); UserLending storage userLending = userLendings[lendingInfo.user][ lendingInfo.userLendingIndex ]; require( lendingInfo.state == UserLendingState.LENDING, "!UserLendingState" ); require( lendingInfo.startedBlock.add(userLending.borrowNumbers).sub( liquidateThresholdBlockNumbers ) < block.number, "!borrowNumbers" ); PoolInfo storage pool = poolInfo[lendingInfo.pid]; lendingInfo.state = UserLendingState.LIQUIDATED; BorrowInfo storage borrowInfo = borrowInfos[ generateId(address(0), lendingInfo.pid, userLending.supportPid) ]; borrowInfo.borrowAmount = borrowInfo.borrowAmount.sub( userLending.token0Price ); borrowInfo.supplyAmount = borrowInfo.supplyAmount.sub( userLending.lendingAmount ); Statistic storage statistic = myStatistics[ generateId( lendingInfo.user, lendingInfo.pid, userLending.supportPid ) ]; statistic.totalCollateral = statistic.totalCollateral.sub( userLending.token0 ); statistic.totalBorrow = statistic.totalBorrow.sub( userLending.lendingAmount ); (address underlyToken, uint256 liquidateAmount) = IConvexBooster( convexBooster ).liquidate( pool.convexPid, userLending.curveCoinId, lendingInfo.user, userLending.token0 ); if (underlyToken == ZERO_ADDRESS) { liquidateAmount = liquidateAmount.add(msg.value); ISupplyBooster(supplyBooster).liquidate{value: liquidateAmount}( userLending.lendingId, userLending.borrowInterest ); } else { IERC20(underlyToken).safeTransfer(supplyBooster, liquidateAmount); if (_extraErc20Amount > 0) { // Failure without authorization IERC20(underlyToken).safeTransferFrom( msg.sender, supplyBooster, _extraErc20Amount ); } ISupplyBooster(supplyBooster).liquidate( userLending.lendingId, userLending.borrowInterest ); } ILendingSponsor(lendingSponsor).payFee( userLending.lendingId, msg.sender ); uint256 gasSpent = (21000 + gasStart - gasleft()).mul(tx.gasprice); emit Liquidate( userLending.lendingId, lendingInfo.user, liquidateAmount, gasSpent, lendingInfo.state ); } function setLiquidateThresholdBlockNumbers(uint256 _v) public onlyGovernance { require( _v >= MIN_LIQUIDATE_BLOCK_NUMBERS && _v <= MAX_LIQUIDATE_BLOCK_NUMBERS, "!_v" ); liquidateThresholdBlockNumbers = _v; } function setBorrowBlock(uint256 _number, bool _state) public onlyGovernance { require( _number.sub(liquidateThresholdBlockNumbers) > liquidateThresholdBlockNumbers, "!_number" ); borrowBlocks[_number] = _state; emit SetBorrowBlock(_number, borrowBlocks[_number]); } function setLendingThreshold(uint256 _pid, uint256 _v) public onlyGovernance { require( _v >= MIN_LENDING_THRESHOLD && _v <= MAX_LENDING_THRESHOLD, "!_v" ); PoolInfo storage pool = poolInfo[_pid]; pool.lendingThreshold = _v; } function setLiquidateThreshold(uint256 _pid, uint256 _v) public onlyGovernance { require( _v >= MIN_LIQUIDATE_THRESHOLD && _v <= MAX_LIQUIDATE_THRESHOLD, "!_v" ); PoolInfo storage pool = poolInfo[_pid]; pool.liquidateThreshold = _v; } receive() external payable {} /* @param _convexBoosterPid convexBooster contract @param _supplyBoosterPids supply contract @param _curveCoinIds curve coin id of curve COINS */ function addMarketPool( uint256 _convexBoosterPid, uint256[] calldata _supplyBoosterPids, int128[] calldata _curveCoinIds, uint256 _lendingThreshold, uint256 _liquidateThreshold ) public onlyGovernance { require( _lendingThreshold >= MIN_LENDING_THRESHOLD && _lendingThreshold <= MAX_LENDING_THRESHOLD, "!_lendingThreshold" ); require( _liquidateThreshold >= MIN_LIQUIDATE_THRESHOLD && _liquidateThreshold <= MAX_LIQUIDATE_THRESHOLD, "!_liquidateThreshold" ); require( _supplyBoosterPids.length == _curveCoinIds.length, "!_supportPids && _curveCoinIds" ); poolInfo.push( PoolInfo({ convexPid: _convexBoosterPid, supportPids: _supplyBoosterPids, curveCoinIds: _curveCoinIds, lendingThreshold: _lendingThreshold, liquidateThreshold: _liquidateThreshold, borrowIndex: 0 }) ); } /* function toBytes16(uint256 x) internal pure returns (bytes16 b) { return bytes16(bytes32(x)); } */ function generateId( address x, uint256 y, uint256 z ) public pure returns (bytes32) { /* return toBytes16(uint256(keccak256(abi.encodePacked(x, y, z)))); */ return keccak256(abi.encodePacked(x, y, z)); } function poolLength() public view returns (uint256) { return poolInfo.length; } function cursor( uint256 _pid, uint256 _offset, uint256 _size ) public view returns (bytes32[] memory, uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 size = _offset.add(_size) > pool.borrowIndex ? pool.borrowIndex.sub(_offset) : _size; bytes32[] memory userLendingIds = new bytes32[](size); for (uint256 i = 0; i < size; i++) { bytes32 userLendingId = poolLending[_pid][_offset.add(i)]; userLendingIds[i] = userLendingId; } return (userLendingIds, pool.borrowIndex); } function calculateRepayAmount(bytes32 _lendingId) public view returns (uint256) { LendingInfo storage lendingInfo = lendings[_lendingId]; UserLending storage userLending = userLendings[lendingInfo.user][ lendingInfo.userLendingIndex ]; if (lendingInfo.state == UserLendingState.LIQUIDATED) return 0; return userLending.lendingAmount; } function getPoolSupportPids(uint256 _pid) public view returns (uint256[] memory) { PoolInfo storage pool = poolInfo[_pid]; return pool.supportPids; } function getCurveCoinId(uint256 _pid, uint256 _supportPid) public view returns (int128) { PoolInfo storage pool = poolInfo[_pid]; return pool.curveCoinIds[_supportPid]; } function getUserLendingState(bytes32 _lendingId) public view returns (UserLendingState) { LendingInfo storage lendingInfo = lendings[_lendingId]; return lendingInfo.state; } function getLendingInfo( uint256 _token0, uint256 _convexPid, int128 _curveCoinId, uint256 _supplyPid, uint256 _lendingThreshold, uint256 _liquidateThreshold, uint256 _borrowBlocks ) public view returns (LendingParams memory) { (address lpToken, uint256 token0Price) = _getCurveInfo( _convexPid, _curveCoinId, _token0 ); uint256 utilizationRate = ISupplyBooster(supplyBooster) .getUtilizationRate(_supplyPid); uint256 supplyRatePerBlock = ISupplyBooster(supplyBooster) .getBorrowRatePerBlock(_supplyPid); uint256 supplyRate = getSupplyRate(supplyRatePerBlock, _borrowBlocks); uint256 lendflareTotalRate; if (utilizationRate > 0) { lendflareTotalRate = getLendingRate( supplyRate, getAmplificationFactor(utilizationRate) ); } else { lendflareTotalRate = supplyRate.sub(SUPPLY_RATE_DENOMINATOR); } uint256 lendingAmount = token0Price.mul(SUPPLY_RATE_DENOMINATOR); lendingAmount = lendingAmount.mul( THRESHOLD_DENOMINATOR.sub(_lendingThreshold).sub( _liquidateThreshold ) ); lendingAmount = lendingAmount.div(THRESHOLD_DENOMINATOR); uint256 repayBorrowAmount = lendingAmount.div(SUPPLY_RATE_DENOMINATOR); uint256 borrowAmount = lendingAmount.div( SUPPLY_RATE_DENOMINATOR.add(lendflareTotalRate) ); uint256 borrowInterest = repayBorrowAmount.sub(borrowAmount); return LendingParams({ lendingAmount: repayBorrowAmount, borrowAmount: borrowAmount, borrowInterest: borrowInterest, lendingRate: lendflareTotalRate, utilizationRate: utilizationRate, supplyRatePerBlock: supplyRatePerBlock, lpToken: lpToken, token0Price: token0Price }); } function getUserLendingsLength(address _user) public view returns (uint256) { return userLendings[_user].length; } function getSupplyRate(uint256 _supplyBlockRate, uint256 n) public pure returns ( uint256 total // _supplyBlockRate and the result are scaled to 1e18 ) { uint256 term = 1e18; // term0 = xn, term1 = n(n-1)/2! * x^2, term2 = term1 * (n - 2) / (i + 1) * x uint256 result = 1e18; // partial sum of terms uint256 MAX_TERMS = 10; // up to MAX_TERMS are calculated, the error is negligible for (uint256 i = 0; i < MAX_TERMS && i < n; ++i) { term = term.mul(n - i).div(i + 1).mul(_supplyBlockRate).div(1e18); total = total.add(term); } total = total.add(result); } function getAmplificationFactor(uint256 _utilizationRate) public pure returns (uint256) { if (_utilizationRate <= 0.9 * 1e18) { return uint256(10).mul(_utilizationRate).div(9).add(1e18); } return uint256(20).mul(_utilizationRate).sub(16 * 1e18); } // lendflare total rate function getLendingRate(uint256 _supplyRate, uint256 _amplificationFactor) public pure returns (uint256) { return _supplyRate.sub(1e18).mul(_amplificationFactor).div(1e18); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./supply/SupplyTreasuryFundForCompound.sol"; import "./convex/IConvexBooster.sol"; import "./supply/ISupplyBooster.sol"; /* This contract will be executed after the lending contracts is created and will become invalid in the future. */ interface ILendingMarket { function addMarketPool( uint256 _convexBoosterPid, uint256[] calldata _supplyBoosterPids, int128[] calldata _curveCoinIds, uint256 _lendingThreshold, uint256 _liquidateThreshold ) external; } interface ISupplyRewardFactoryExtra is ISupplyRewardFactory { function addOwner(address _newOwner) external; } contract GenerateLendingPools { address public convexBooster; address public lendingMarket; address public supplyBooster; address public supplyRewardFactory; bool public completed; address public deployer; struct ConvexPool { address target; uint256 pid; } struct LendingMarketMapping { uint256 convexBoosterPid; uint256[] supplyBoosterPids; int128[] curveCoinIds; } address[] public supplyPools; address[] public compoundPools; ConvexPool[] public convexPools; LendingMarketMapping[] public lendingMarketMappings; constructor(address _deployer) public { deployer = _deployer; } function setLendingContract( address _supplyBooster, address _convexBooster, address _lendingMarket, address _supplyRewardFactory ) public { require( deployer == msg.sender, "GenerateLendingPools: !authorized auth" ); supplyBooster = _supplyBooster; convexBooster = _convexBooster; lendingMarket = _lendingMarket; supplyRewardFactory = _supplyRewardFactory; } function createMapping( uint256 _convexBoosterPid, uint256 _param1, uint256 _param2, int128 _param3, int128 _param4 ) internal pure returns (LendingMarketMapping memory lendingMarketMapping) { uint256[] memory supplyBoosterPids = new uint256[](2); int128[] memory curveCoinIds = new int128[](2); supplyBoosterPids[0] = _param1; supplyBoosterPids[1] = _param2; curveCoinIds[0] = _param3; curveCoinIds[1] = _param4; lendingMarketMapping.convexBoosterPid = _convexBoosterPid; lendingMarketMapping.supplyBoosterPids = supplyBoosterPids; lendingMarketMapping.curveCoinIds = curveCoinIds; } function createMapping( uint256 _convexBoosterPid, uint256 _param1, int128 _param2 ) internal pure returns (LendingMarketMapping memory lendingMarketMapping) { uint256[] memory supplyBoosterPids = new uint256[](1); int128[] memory curveCoinIds = new int128[](1); supplyBoosterPids[0] = _param1; curveCoinIds[0] = _param2; lendingMarketMapping.convexBoosterPid = _convexBoosterPid; lendingMarketMapping.supplyBoosterPids = supplyBoosterPids; lendingMarketMapping.curveCoinIds = curveCoinIds; } function generateSupplyPools() internal { address compoundComptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; (address USDC,address cUSDC) = (0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 0x39AA39c021dfbaE8faC545936693aC917d5E7563); (address DAI,address cDAI) = (0x6B175474E89094C44Da98b954EedeAC495271d0F, 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); (address TUSD,address cTUSD) = (0x0000000000085d4780B73119b644AE5ecd22b376, 0x12392F67bdf24faE0AF363c24aC620a2f67DAd86); (address WBTC,address cWBTC) = (0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, 0xC11b1268C1A384e55C48c2391d8d480264A3A7F4); (address Ether,address cEther) = (0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); supplyPools.push(USDC); supplyPools.push(DAI); supplyPools.push(TUSD); supplyPools.push(WBTC); supplyPools.push(Ether); compoundPools.push(cUSDC); compoundPools.push(cDAI); compoundPools.push(cTUSD); compoundPools.push(cWBTC); compoundPools.push(cEther); for (uint256 i = 0; i < supplyPools.length; i++) { SupplyTreasuryFundForCompound supplyTreasuryFund = new SupplyTreasuryFundForCompound( supplyBooster, compoundPools[i], compoundComptroller, supplyRewardFactory ); ISupplyRewardFactoryExtra(supplyRewardFactory).addOwner(address(supplyTreasuryFund)); ISupplyBooster(supplyBooster).addSupplyPool( supplyPools[i], address(supplyTreasuryFund) ); } } function generateConvexPools() internal { // USDC,DAI , supplyBoosterPids, curveCoinIds = [cUSDC, cDAI], [USDC, DAI] convexPools.push( ConvexPool(0xC25a3A3b969415c80451098fa907EC722572917F, 4) ); // DAI USDC USDT sUSD [1, 0] [0, 1] sUSD convexPools.push( ConvexPool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B, 40) ); // MIM DAI USDC USDT [1, 0] [1, 2] mim convexPools.push( ConvexPool(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490, 9) ); // DAI USDC USDT [1, 0] [0, 1] 3Pool convexPools.push( ConvexPool(0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B, 32) ); // FRAX DAI USDC USDT [1, 0] [1, 2] frax convexPools.push( ConvexPool(0x1AEf73d49Dedc4b1778d0706583995958Dc862e6, 14) ); // mUSD + 3Crv [1, 0] [1, 2] musd convexPools.push( ConvexPool(0x94e131324b6054c0D789b190b2dAC504e4361b53, 21) ); // UST + 3Crv [1, 0] [1, 2] ust convexPools.push( ConvexPool(0xEd279fDD11cA84bEef15AF5D39BB4d4bEE23F0cA, 33) ); // LUSD + 3Crv [1, 0] [1, 2] lusd convexPools.push( ConvexPool(0x43b4FdFD4Ff969587185cDB6f0BD875c5Fc83f8c, 36) ); // alUSD + 3Crv [1, 0] [1, 2] alusd convexPools.push( ConvexPool(0xD2967f45c4f384DEEa880F807Be904762a3DeA07, 10) ); // GUSD + 3Crv [1, 0] [1, 2] gusd convexPools.push( ConvexPool(0x4f3E8F405CF5aFC05D68142F3783bDfE13811522, 13) ); // USDN + 3Crv [1, 0] [1, 2] usdn convexPools.push( ConvexPool(0x97E2768e8E73511cA874545DC5Ff8067eB19B787, 12) ); // USDK + 3Crv [1, 0] [1, 2] usdk convexPools.push( ConvexPool(0x4807862AA8b2bF68830e4C8dc86D0e9A998e085a, 34) ); // BUSD + 3Crv [1, 0] [1, 2] busdv2 convexPools.push( ConvexPool(0x5B5CFE992AdAC0C9D48E05854B2d91C73a003858, 11) ); // HUSD + 3Crv [1, 0] [1, 2] husd convexPools.push( ConvexPool(0xC2Ee6b0334C261ED60C72f6054450b61B8f18E35, 15) ); // RSV + 3Crv [1, 0] [1, 2] rsv convexPools.push( ConvexPool(0x3a664Ab939FD8482048609f652f9a0B0677337B9, 17) ); // DUSD + 3Crv [1, 0] [1, 2] dusd convexPools.push( ConvexPool(0x7Eb40E450b9655f4B3cC4259BCC731c63ff55ae6, 28) ); // USDP + 3Crv [1, 0] [1, 2] usdp // TUSD convexPools.push( ConvexPool(0xEcd5e75AFb02eFa118AF914515D6521aaBd189F1, 31) ); // TUSD + 3Crv [2] [0] tusd // WBTC convexPools.push( ConvexPool(0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3, 7) ); // renBTC + wBTC + sBTC [3] [1] sbtc convexPools.push( ConvexPool(0x2fE94ea3d5d4a175184081439753DE15AeF9d614, 20) ); // oBTC + renBTC + wBTC + sBTC [3] [2] obtc convexPools.push( ConvexPool(0x49849C98ae39Fff122806C06791Fa73784FB3675, 6) ); // renBTC + wBTC [3] [1] ren convexPools.push( ConvexPool(0xb19059ebb43466C323583928285a49f558E572Fd, 8) ); // HBTC + wBTC [3] [1] hbtc convexPools.push( ConvexPool(0x410e3E86ef427e30B9235497143881f717d93c2A, 19) ); // BBTC + renBTC + wBTC + sBTC [3] [2] bbtc convexPools.push( ConvexPool(0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd, 16) ); // tBTC + renBTC + wBTC + sBTC [3] [2] tbtc convexPools.push( ConvexPool(0xDE5331AC4B3630f94853Ff322B66407e0D6331E8, 18) ); // pBTC + renBTC + wBTC + sBTC [3] [2] pbtc // ETH convexPools.push( ConvexPool(0xA3D87FffcE63B53E0d54fAa1cc983B7eB0b74A9c, 23) ); // ETH + sETH [4] [0] seth convexPools.push( ConvexPool(0x06325440D014e39736583c165C2963BA99fAf14E, 25) ); // ETH + stETH [4] [0] steth convexPools.push( ConvexPool(0xaA17A236F2bAdc98DDc0Cf999AbB47D47Fc0A6Cf, 27) ); // ETH + ankrETH [4] [0] ankreth convexPools.push( ConvexPool(0x53a901d48795C58f485cBB38df08FA96a24669D5, 35) ); // ETH + rETH [4] [0] reth for (uint256 i = 0; i < convexPools.length; i++) { IConvexBooster(convexBooster).addConvexPool(convexPools[i].pid); } } function generateMappingPools() internal { lendingMarketMappings.push(createMapping(0, 1, 0, 0, 1)); // [1, 0] [0, 1] lendingMarketMappings.push(createMapping(1, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(2, 1, 0, 0, 1)); // [1, 0] [0, 1] lendingMarketMappings.push(createMapping(3, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(4, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(5, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(6, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(7, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(8, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(9, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(10, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(11, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(12, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(13, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(14, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(15, 1, 0, 1, 2)); // [1, 0] [1, 2] lendingMarketMappings.push(createMapping(16, 2, 0)); // [2] [0] lendingMarketMappings.push(createMapping(17, 3, 1)); // [3] [1] lendingMarketMappings.push(createMapping(18, 3, 2)); // [3] [2] lendingMarketMappings.push(createMapping(19, 3, 1)); // [3] [1] lendingMarketMappings.push(createMapping(20, 3, 1)); // [3] [1] lendingMarketMappings.push(createMapping(21, 3, 2)); // [3] [2] lendingMarketMappings.push(createMapping(22, 3, 2)); // [3] [2] lendingMarketMappings.push(createMapping(23, 3, 2)); // [3] [2] lendingMarketMappings.push(createMapping(24, 4, 0)); // [4] [0] lendingMarketMappings.push(createMapping(25, 4, 0)); // [4] [0] lendingMarketMappings.push(createMapping(26, 4, 0)); // [4] [0] lendingMarketMappings.push(createMapping(27, 4, 0)); // [4] [0] for (uint256 i = 0; i < lendingMarketMappings.length; i++) { ILendingMarket(lendingMarket).addMarketPool( lendingMarketMappings[i].convexBoosterPid, lendingMarketMappings[i].supplyBoosterPids, lendingMarketMappings[i].curveCoinIds, 100, 50 ); } } function run() public { require(deployer == msg.sender, "GenerateLendingPools: !authorized auth"); require(!completed, "GenerateLendingPools: !completed"); require(supplyBooster != address(0),"!supplyBooster"); require(convexBooster != address(0),"!convexBooster"); require(lendingMarket != address(0),"!lendingMarket"); require(supplyRewardFactory != address(0),"!supplyRewardFactory"); generateSupplyPools(); generateConvexPools(); generateMappingPools(); completed = true; } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "./IConvexBooster.sol"; interface IOriginConvexBooster { function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); function withdraw(uint256 _pid, uint256 _amount) external returns(bool); function claimStashToken(address _token, address _rewardAddress, address _lfRewardAddress, uint256 _rewards) external; function poolInfo(uint256) external view returns(address,address,address,address,address, bool); function isShutdown() external view returns(bool); function minter() external view returns(address); function earmarkRewards(uint256) external returns(bool); } interface IOriginConvexRewardPool { function getReward() external returns(bool); function getReward(address _account, bool _claimExtras) external returns(bool); function withdrawAllAndUnwrap(bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external returns(bool); function withdrawAll(bool claim) external; function withdraw(uint256 amount, bool claim) external returns(bool); function stakeFor(address _for, uint256 _amount) external returns(bool); function stakeAll() external returns(bool); function stake(uint256 _amount) external returns(bool); function earned(address account) external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardToken() external returns(address); function extraRewards(uint256 _idx) external view returns (address); function extraRewardsLength() external view returns (uint256); } interface IOriginConvexVirtualBalanceRewardPool { function getReward(address _account) external; function getReward() external; function rewardToken() external returns(address); } interface IConvexRewardPool { function earned(address account) external view returns (uint256); function stake(address _for) external; function withdraw(address _for) external; function getReward(address _for) external; function notifyRewardAmount(uint256 reward) external; function extraRewards(uint256 _idx) external view returns (address); function extraRewardsLength() external view returns (uint256); function addExtraReward(address _reward) external returns(bool); } interface IConvexRewardFactory { function createReward(address _reward, address _virtualBalance, address _operator) external returns (address); } interface ICurveSwap { function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external; /* function remove_liquidity(uint256 _token_amount, uint256[] memory min_amounts) external; */ function coins(uint256 _coinId) external view returns(address); function balances(uint256 _coinId) external view returns(uint256); } interface ICurveAddressProvider{ function get_registry() external view returns(address); function get_address(uint256 _id) external view returns(address); } interface ICurveRegistry{ function gauge_controller() external view returns(address); function get_lp_token(address) external view returns(address); function get_pool_from_lp_token(address) external view returns(address); function get_gauges(address) external view returns(address[10] memory,uint128[10] memory); } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./convex/ConvexInterfaces.sol"; import "./common/IVirtualBalanceWrapper.sol"; contract ConvexBooster is Initializable, ReentrancyGuard, IConvexBooster { using Address for address payable; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // https://curve.readthedocs.io/registry-address-provider.html ICurveAddressProvider public curveAddressProvider; address public constant ZERO_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public convexRewardFactory; address public virtualBalanceWrapperFactory; address public originConvexBooster; address public rewardCrvToken; address public rewardCvxToken; uint256 public version; address public lendingMarket; address public owner; address public governance; struct PoolInfo { uint256 originConvexPid; address curveSwapAddress; /* like 3pool https://github.com/curvefi/curve-js/blob/master/src/constants/abis/abis-ethereum.ts */ address lpToken; address originCrvRewards; address originStash; address virtualBalance; address rewardCrvPool; address rewardCvxPool; bool shutdown; } PoolInfo[] public override poolInfo; mapping(uint256 => mapping(address => uint256)) public frozenTokens; // pid => (user => amount) event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); event UpdateExtraRewards(uint256 pid, uint256 index, address extraReward); event Initialized(address indexed thisAddress); event ToggleShutdownPool(uint256 pid, bool shutdown); event SetOwner(address owner); event SetGovernance(address governance); modifier onlyOwner() { require(owner == msg.sender, "ConvexBooster: caller is not the owner"); _; } modifier onlyGovernance() { require( governance == msg.sender, "ConvexBooster: caller is not the governance" ); _; } modifier onlyLendingMarket() { require( lendingMarket == msg.sender, "ConvexBooster: caller is not the lendingMarket" ); _; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } /* The default governance user is GenerateLendingPools contract. It will be set to DAO in the future */ function setGovernance(address _governance) public onlyOwner { governance = _governance; emit SetGovernance(_governance); } function setLendingMarket(address _v) public onlyOwner { require(_v != address(0), "!_v"); lendingMarket = _v; } function initialize( address _owner, address _originConvexBooster, address _convexRewardFactory, address _virtualBalanceWrapperFactory, address _rewardCrvToken, address _rewardCvxToken ) public initializer { owner = _owner; governance = _owner; convexRewardFactory = _convexRewardFactory; originConvexBooster = _originConvexBooster; virtualBalanceWrapperFactory = _virtualBalanceWrapperFactory; rewardCrvToken = _rewardCrvToken; rewardCvxToken = _rewardCvxToken; version = 1; curveAddressProvider = ICurveAddressProvider( 0x0000000022D53366457F9d5E68Ec105046FC4383 ); emit Initialized(address(this)); } function addConvexPool(uint256 _originConvexPid) public override onlyGovernance { ( address lpToken, , , address originCrvRewards, address originStash, bool shutdown ) = IOriginConvexBooster(originConvexBooster).poolInfo( _originConvexPid ); require(!shutdown, "!shutdown"); require(lpToken != address(0), "!lpToken"); ICurveRegistry registry = ICurveRegistry( ICurveAddressProvider(curveAddressProvider).get_registry() ); address curveSwapAddress = registry.get_pool_from_lp_token(lpToken); address virtualBalance = IVirtualBalanceWrapperFactory( virtualBalanceWrapperFactory ).createWrapper(address(this)); address rewardCrvPool = IConvexRewardFactory(convexRewardFactory) .createReward(rewardCrvToken, virtualBalance, address(this)); address rewardCvxPool = IConvexRewardFactory(convexRewardFactory) .createReward(rewardCvxToken, virtualBalance, address(this)); uint256 extraRewardsLength = IOriginConvexRewardPool(originCrvRewards) .extraRewardsLength(); if (extraRewardsLength > 0) { for (uint256 i = 0; i < extraRewardsLength; i++) { address extraRewardToken = IOriginConvexRewardPool( originCrvRewards ).extraRewards(i); address extraRewardPool = IConvexRewardFactory( convexRewardFactory ).createReward( IOriginConvexRewardPool(extraRewardToken).rewardToken(), virtualBalance, address(this) ); IConvexRewardPool(rewardCrvPool).addExtraReward( extraRewardPool ); } } poolInfo.push( PoolInfo({ originConvexPid: _originConvexPid, curveSwapAddress: curveSwapAddress, lpToken: lpToken, originCrvRewards: originCrvRewards, originStash: originStash, virtualBalance: virtualBalance, rewardCrvPool: rewardCrvPool, rewardCvxPool: rewardCvxPool, shutdown: false }) ); } function updateExtraRewards(uint256 _pid) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; ( , , , address originCrvRewards, , bool shutdown ) = IOriginConvexBooster(originConvexBooster).poolInfo( pool.originConvexPid ); require(!shutdown, "!shutdown"); uint256 originExtraRewardsLength = IOriginConvexRewardPool( originCrvRewards ).extraRewardsLength(); uint256 currentExtraRewardsLength = IConvexRewardPool( pool.rewardCrvPool ).extraRewardsLength(); for ( uint256 i = currentExtraRewardsLength; i < originExtraRewardsLength; i++ ) { address extraRewardToken = IOriginConvexRewardPool(originCrvRewards) .extraRewards(i); address extraRewardPool = IConvexRewardFactory(convexRewardFactory) .createReward( IOriginConvexRewardPool(extraRewardToken).rewardToken(), pool.virtualBalance, address(this) ); IConvexRewardPool(pool.rewardCrvPool).addExtraReward( extraRewardPool ); emit UpdateExtraRewards(_pid, i, extraRewardPool); } } function toggleShutdownPool(uint256 _pid) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; pool.shutdown = !pool.shutdown; emit ToggleShutdownPool(_pid, pool.shutdown); } function depositFor( uint256 _pid, uint256 _amount, address _user ) public override onlyLendingMarket nonReentrant returns (bool) { PoolInfo storage pool = poolInfo[_pid]; IERC20(pool.lpToken).safeTransferFrom( msg.sender, address(this), _amount ); // ( // address lpToken, // address token, // address gauge, // address crvRewards, // address stash, // bool shutdown // ) = IOriginConvexBooster(convexBooster).poolInfo(pool.convexPid); (, , , , , bool shutdown) = IOriginConvexBooster(originConvexBooster) .poolInfo(pool.originConvexPid); require(!shutdown, "!convex shutdown"); require(!pool.shutdown, "!shutdown"); IERC20(pool.lpToken).safeApprove(originConvexBooster, 0); IERC20(pool.lpToken).safeApprove(originConvexBooster, _amount); IOriginConvexBooster(originConvexBooster).deposit( pool.originConvexPid, _amount, true ); IConvexRewardPool(pool.rewardCrvPool).stake(_user); IConvexRewardPool(pool.rewardCvxPool).stake(_user); IVirtualBalanceWrapper(pool.virtualBalance).stakeFor(_user, _amount); emit Deposited(_user, _pid, _amount); return true; } function withdrawMyTokens(uint256 _pid, uint256 _amount) public nonReentrant { require(_amount > 0, "!_amount"); PoolInfo storage pool = poolInfo[_pid]; frozenTokens[_pid][msg.sender] = frozenTokens[_pid][msg.sender].sub( _amount ); IOriginConvexRewardPool(pool.originCrvRewards).withdrawAndUnwrap( _amount, true ); IERC20(pool.lpToken).safeTransfer(msg.sender, _amount); } function withdrawFor( uint256 _pid, uint256 _amount, address _user, bool _frozenTokens ) public override onlyLendingMarket nonReentrant returns (bool) { PoolInfo storage pool = poolInfo[_pid]; if (_frozenTokens) { frozenTokens[_pid][_user] = frozenTokens[_pid][_user].add(_amount); } else { IOriginConvexRewardPool(pool.originCrvRewards).withdrawAndUnwrap( _amount, true ); IERC20(pool.lpToken).safeTransfer(_user, _amount); } if (IConvexRewardPool(pool.rewardCrvPool).earned(_user) > 0) { IConvexRewardPool(pool.rewardCrvPool).getReward(_user); } if (IConvexRewardPool(pool.rewardCvxPool).earned(_user) > 0) { IConvexRewardPool(pool.rewardCvxPool).getReward(_user); } IVirtualBalanceWrapper(pool.virtualBalance).withdrawFor(_user, _amount); IConvexRewardPool(pool.rewardCrvPool).withdraw(_user); IConvexRewardPool(pool.rewardCvxPool).withdraw(_user); emit Withdrawn(_user, _pid, _amount); return true; } function liquidate( uint256 _pid, int128 _coinId, address _user, uint256 _amount ) external override onlyLendingMarket nonReentrant returns (address, uint256) { PoolInfo storage pool = poolInfo[_pid]; IOriginConvexRewardPool(pool.originCrvRewards).withdrawAndUnwrap( _amount, true ); IVirtualBalanceWrapper(pool.virtualBalance).withdrawFor(_user, _amount); if (IConvexRewardPool(pool.rewardCrvPool).earned(_user) > 0) { IConvexRewardPool(pool.rewardCrvPool).getReward(_user); } if (IConvexRewardPool(pool.rewardCvxPool).earned(_user) > 0) { IConvexRewardPool(pool.rewardCvxPool).getReward(_user); } IConvexRewardPool(pool.rewardCrvPool).withdraw(_user); IConvexRewardPool(pool.rewardCvxPool).withdraw(_user); IERC20(pool.lpToken).safeApprove(pool.curveSwapAddress, 0); IERC20(pool.lpToken).safeApprove(pool.curveSwapAddress, _amount); address underlyToken = ICurveSwap(pool.curveSwapAddress).coins( uint256(_coinId) ); ICurveSwap(pool.curveSwapAddress).remove_liquidity_one_coin( _amount, _coinId, 0 ); if (underlyToken == ZERO_ADDRESS) { uint256 totalAmount = address(this).balance; msg.sender.sendValue(totalAmount); return (ZERO_ADDRESS, totalAmount); } else { uint256 totalAmount = IERC20(underlyToken).balanceOf(address(this)); IERC20(underlyToken).safeTransfer(msg.sender, totalAmount); return (underlyToken, totalAmount); } } function getRewards(uint256 _pid) public nonReentrant { PoolInfo memory pool = poolInfo[_pid]; if (IConvexRewardPool(pool.rewardCrvPool).earned(msg.sender) > 0) { IConvexRewardPool(pool.rewardCrvPool).getReward(msg.sender); } if (IConvexRewardPool(pool.rewardCvxPool).earned(msg.sender) > 0) { IConvexRewardPool(pool.rewardCvxPool).getReward(msg.sender); } } function claimRewardToken(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IOriginConvexRewardPool(pool.originCrvRewards).getReward( address(this), true ); address rewardUnderlyToken = IOriginConvexRewardPool( pool.originCrvRewards ).rewardToken(); uint256 crvBalance = IERC20(rewardUnderlyToken).balanceOf( address(this) ); if (crvBalance > 0) { IERC20(rewardUnderlyToken).safeTransfer( pool.rewardCrvPool, crvBalance ); IConvexRewardPool(pool.rewardCrvPool).notifyRewardAmount( crvBalance ); } uint256 extraRewardsLength = IConvexRewardPool(pool.rewardCrvPool) .extraRewardsLength(); for (uint256 i = 0; i < extraRewardsLength; i++) { address currentExtraReward = IConvexRewardPool(pool.rewardCrvPool) .extraRewards(i); address originExtraRewardToken = IOriginConvexRewardPool( pool.originCrvRewards ).extraRewards(i); address extraRewardUnderlyToken = IOriginConvexVirtualBalanceRewardPool( originExtraRewardToken ).rewardToken(); IOriginConvexVirtualBalanceRewardPool(originExtraRewardToken) .getReward(address(this)); uint256 extraBalance = IERC20(extraRewardUnderlyToken).balanceOf( address(this) ); if (extraBalance > 0) { IERC20(extraRewardUnderlyToken).safeTransfer( currentExtraReward, extraBalance ); IConvexRewardPool(currentExtraReward).notifyRewardAmount( extraBalance ); } } /* cvx */ uint256 cvxBal = IERC20(rewardCvxToken).balanceOf(address(this)); if (cvxBal > 0) { IERC20(rewardCvxToken).safeTransfer(pool.rewardCvxPool, cvxBal); IConvexRewardPool(pool.rewardCvxPool).notifyRewardAmount(cvxBal); } } function claimAllRewardToken() public { for (uint256 i = 0; i < poolInfo.length; i++) { claimRewardToken(i); } } receive() external payable {} /* view functions */ function poolLength() external view returns (uint256) { return poolInfo.length; } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./ConvexInterfaces.sol"; import "../common/IVirtualBalanceWrapper.sol"; contract ConvexRewardPool is ReentrancyGuard, IConvexRewardPool { using Address for address payable; using SafeMath for uint256; using SafeERC20 for IERC20; address public rewardToken; uint256 public constant duration = 7 days; address public owner; address public virtualBalance; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; address[] public override extraRewards; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user); event Withdrawn(address indexed user); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } constructor( address _reward, address _virtualBalance, address _owner ) public { rewardToken = _reward; virtualBalance = _virtualBalance; owner = _owner; } function totalSupply() public view returns (uint256) { return IVirtualBalanceWrapper(virtualBalance).totalSupply(); } function balanceOf(address _for) public view returns (uint256) { return IVirtualBalanceWrapper(virtualBalance).balanceOf(_for); } function extraRewardsLength() external view override returns (uint256) { return extraRewards.length; } function addExtraReward(address _reward) external override returns (bool) { require( msg.sender == owner, "ConvexRewardPool: !authorized addExtraReward" ); require(_reward != address(0), "!reward setting"); extraRewards.push(_reward); return true; } function clearExtraRewards() external { require( msg.sender == owner, "ConvexRewardPool: !authorized clearExtraRewards" ); delete extraRewards; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address _for) public view override returns (uint256) { uint256 total = balanceOf(_for) .mul(rewardPerToken().sub(userRewardPerTokenPaid[_for])) .div(1e18) .add(rewards[_for]); for (uint256 i = 0; i < extraRewards.length; i++) { total = total.add(IConvexRewardPool(extraRewards[i]).earned(_for)); } return total; } function stake(address _for) public override nonReentrant updateReward(_for) { require(msg.sender == owner, "ConvexRewardPool: !authorized stake"); emit Staked(_for); } function withdraw(address _for) public override nonReentrant updateReward(_for) { require(msg.sender == owner, "ConvexRewardPool: !authorized withdraw"); emit Withdrawn(_for); } function getReward(address _for) public override nonReentrant updateReward(_for) { uint256 reward = earned(_for); if (reward > 0) { rewards[_for] = 0; if (rewardToken != address(0)) { IERC20(rewardToken).safeTransfer(_for, reward); } else { require( address(this).balance >= reward, "!address(this).balance" ); payable(_for).sendValue(reward); } emit RewardPaid(_for, reward); } for (uint256 i = 0; i < extraRewards.length; i++) { IConvexRewardPool(extraRewards[i]).getReward(_for); } } function notifyRewardAmount(uint256 reward) external override updateReward(address(0)) { require( msg.sender == owner, "ConvexRewardPool: !authorized notifyRewardAmount" ); // overflow fix according to https://sips.synthetix.io/sips/sip-77 require( reward < uint256(-1) / 1e18, "the notified reward cannot invoke multiplication overflow" ); if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); emit RewardAdded(reward); } receive() external payable {} } contract ConvexRewardFactory { address public owner; event CreateReward(IConvexRewardPool rewardPool, address rewardToken); constructor() public { owner = msg.sender; } function setOwner(address _owner) external { require( msg.sender == owner, "ConvexRewardFactory: !authorized setOwner" ); owner = _owner; } function createReward( address _rewardToken, address _virtualBalance, address _owner ) external returns (address) { require( msg.sender == owner, "ConvexRewardFactory: !authorized createReward" ); IConvexRewardPool rewardPool = IConvexRewardPool( address(new ConvexRewardPool(_rewardToken, _virtualBalance, _owner)) ); emit CreateReward(rewardPool, _rewardToken); return address(rewardPool); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "./ConvexInterfaces.sol"; import "./IConvexBoosterV2.sol"; interface ICurveSwapV2 is ICurveSwap { // function remove_liquidity_one_coin( // uint256 _token_amount, // int128 _i, // uint256 _min_amount // ) external override; function remove_liquidity_one_coin( address _pool, uint256 _burn_amount, int128 _i, uint256 _min_amount ) external; // function coins(uint256 _coinId) external view returns(address); in ICurveSwap function coins(int128 _coinId) external view returns (address); function balances(uint256 _coinId) external view override returns (uint256); function get_virtual_price() external view returns (uint256); function calc_withdraw_one_coin(uint256 _tokenAmount, int128 _tokenId) external view returns (uint256); /* factory */ function calc_withdraw_one_coin( address _pool, uint256 _tokenAmount, int128 _tokenId ) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./convex/ConvexInterfacesV2.sol"; import "./common/IVirtualBalanceWrapper.sol"; contract ConvexBoosterV2 is Initializable, ReentrancyGuard, IConvexBoosterV2 { using Address for address payable; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // https://curve.readthedocs.io/registry-address-provider.html ICurveAddressProvider public curveAddressProvider; address public constant ZERO_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public convexRewardFactory; address public virtualBalanceWrapperFactory; address public originConvexBooster; address public rewardCrvToken; address public rewardCvxToken; uint256 public version; address public lendingMarket; address public owner; address public governance; struct PoolInfo { uint256 originConvexPid; address curveSwapAddress; /* like 3pool https://github.com/curvefi/curve-js/blob/master/src/constants/abis/abis-ethereum.ts */ address lpToken; address originCrvRewards; address originStash; address virtualBalance; address rewardCrvPool; address rewardCvxPool; bool shutdown; } struct MetaPoolInfo { address swapAddress; address zapAddress; address basePoolAddress; bool isMeta; bool isMetaFactory; } PoolInfo[] public override poolInfo; mapping(uint256 => mapping(address => uint256)) public frozenTokens; // pid => (user => amount) mapping(address => MetaPoolInfo) public metaPoolInfo; event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); event UpdateExtraRewards(uint256 pid, uint256 index, address extraReward); event Initialized(address indexed thisAddress); event ToggleShutdownPool(uint256 pid, bool shutdown); event SetOwner(address owner); event SetGovernance(address governance); event CurveZap(address lpToken, address curveZapAddress); event SetLendingMarket(address lendingMarket); event AddConvexPool( uint256 originConvexPid, address lpToken, address curveSwapAddress ); event RemoveLiquidity( address lpToken, address curveSwapAddress, uint256 amount, int128 coinId ); event ClaimRewardToken(uint256 pid); modifier onlyOwner() { require(owner == msg.sender, "ConvexBooster: caller is not the owner"); _; } modifier onlyGovernance() { require( governance == msg.sender, "ConvexBooster: caller is not the governance" ); _; } modifier onlyLendingMarket() { require( lendingMarket == msg.sender, "ConvexBooster: caller is not the lendingMarket" ); _; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } /* The default governance user is GenerateLendingPools contract. It will be set to DAO in the future */ function setGovernance(address _governance) public onlyOwner { governance = _governance; emit SetGovernance(_governance); } function setLendingMarket(address _v) public onlyOwner { require(_v != address(0), "!_v"); lendingMarket = _v; emit SetLendingMarket(lendingMarket); } // @custom:oz-upgrades-unsafe-allow constructor constructor() public initializer {} function initialize( address _owner, address _originConvexBooster, address _convexRewardFactory, address _virtualBalanceWrapperFactory, address _rewardCrvToken, address _rewardCvxToken ) public initializer { owner = _owner; governance = _owner; convexRewardFactory = _convexRewardFactory; originConvexBooster = _originConvexBooster; virtualBalanceWrapperFactory = _virtualBalanceWrapperFactory; rewardCrvToken = _rewardCrvToken; rewardCvxToken = _rewardCvxToken; version = 1; curveAddressProvider = ICurveAddressProvider( 0x0000000022D53366457F9d5E68Ec105046FC4383 ); emit Initialized(address(this)); } function _addConvexPool( uint256 _originConvexPid, address _lpToken, address _originCrvRewards, address _originStash, address _curveSwapAddress ) internal { address virtualBalance = IVirtualBalanceWrapperFactory( virtualBalanceWrapperFactory ).createWrapper(address(this)); address rewardCrvPool = IConvexRewardFactory(convexRewardFactory) .createReward(rewardCrvToken, virtualBalance, address(this)); address rewardCvxPool = IConvexRewardFactory(convexRewardFactory) .createReward(rewardCvxToken, virtualBalance, address(this)); uint256 extraRewardsLength = IOriginConvexRewardPool(_originCrvRewards) .extraRewardsLength(); if (extraRewardsLength > 0) { for (uint256 i = 0; i < extraRewardsLength; i++) { address extraRewardToken = IOriginConvexRewardPool( _originCrvRewards ).extraRewards(i); address extraRewardPool = IConvexRewardFactory( convexRewardFactory ).createReward( IOriginConvexRewardPool(extraRewardToken).rewardToken(), virtualBalance, address(this) ); IConvexRewardPool(rewardCrvPool).addExtraReward( extraRewardPool ); } } poolInfo.push( PoolInfo({ originConvexPid: _originConvexPid, curveSwapAddress: _curveSwapAddress, lpToken: _lpToken, originCrvRewards: _originCrvRewards, originStash: _originStash, virtualBalance: virtualBalance, rewardCrvPool: rewardCrvPool, rewardCvxPool: rewardCvxPool, shutdown: false }) ); emit AddConvexPool(_originConvexPid, _lpToken, _curveSwapAddress); } function addConvexPool(uint256 _originConvexPid) public override onlyGovernance { ( address lpToken, , , address originCrvRewards, address originStash, bool shutdown ) = IOriginConvexBooster(originConvexBooster).poolInfo( _originConvexPid ); require(!shutdown, "!shutdown"); require(lpToken != address(0), "!lpToken"); ICurveRegistry registry = ICurveRegistry( ICurveAddressProvider(curveAddressProvider).get_registry() ); address curveSwapAddress = registry.get_pool_from_lp_token(lpToken); _addConvexPool( _originConvexPid, lpToken, originCrvRewards, originStash, curveSwapAddress ); } // Reference https://curve.readthedocs.io/ref-addresses.html?highlight=zap#deposit-zaps function addConvexPool( uint256 _originConvexPid, address _curveSwapAddress, address _curveZapAddress, address _basePoolAddress, bool _isMeta, bool _isMetaFactory ) public override onlyGovernance { require(_curveSwapAddress != address(0), "!_curveSwapAddress"); require(_curveZapAddress != address(0), "!_curveZapAddress"); require(_basePoolAddress != address(0), "!_basePoolAddress"); ( address lpToken, , , address originCrvRewards, address originStash, bool shutdown ) = IOriginConvexBooster(originConvexBooster).poolInfo( _originConvexPid ); require(!shutdown, "!shutdown"); require(lpToken != address(0), "!lpToken"); metaPoolInfo[lpToken] = MetaPoolInfo( _curveSwapAddress, _curveZapAddress, _basePoolAddress, _isMeta, _isMetaFactory ); _addConvexPool( _originConvexPid, lpToken, originCrvRewards, originStash, _curveSwapAddress ); emit CurveZap(lpToken, _curveZapAddress); } function updateExtraRewards(uint256 _pid) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; ( , , , address originCrvRewards, , bool shutdown ) = IOriginConvexBooster(originConvexBooster).poolInfo( pool.originConvexPid ); require(!shutdown, "!shutdown"); uint256 originExtraRewardsLength = IOriginConvexRewardPool( originCrvRewards ).extraRewardsLength(); uint256 currentExtraRewardsLength = IConvexRewardPool( pool.rewardCrvPool ).extraRewardsLength(); for ( uint256 i = currentExtraRewardsLength; i < originExtraRewardsLength; i++ ) { address extraRewardToken = IOriginConvexRewardPool(originCrvRewards) .extraRewards(i); address extraRewardPool = IConvexRewardFactory(convexRewardFactory) .createReward( IOriginConvexRewardPool(extraRewardToken).rewardToken(), pool.virtualBalance, address(this) ); IConvexRewardPool(pool.rewardCrvPool).addExtraReward( extraRewardPool ); emit UpdateExtraRewards(_pid, i, extraRewardPool); } } function toggleShutdownPool(uint256 _pid) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; pool.shutdown = !pool.shutdown; emit ToggleShutdownPool(_pid, pool.shutdown); } function depositFor( uint256 _pid, uint256 _amount, address _user ) public override onlyLendingMarket nonReentrant returns (bool) { PoolInfo storage pool = poolInfo[_pid]; IERC20(pool.lpToken).safeTransferFrom( msg.sender, address(this), _amount ); /* ( address lpToken, address token, address gauge, address crvRewards, address stash, bool shutdown ) */ (, , , , , bool shutdown) = IOriginConvexBooster(originConvexBooster) .poolInfo(pool.originConvexPid); require(!shutdown, "!convex shutdown"); require(!pool.shutdown, "!shutdown"); IERC20(pool.lpToken).safeApprove(originConvexBooster, 0); IERC20(pool.lpToken).safeApprove(originConvexBooster, _amount); IOriginConvexBooster(originConvexBooster).deposit( pool.originConvexPid, _amount, true ); IConvexRewardPool(pool.rewardCrvPool).stake(_user); IConvexRewardPool(pool.rewardCvxPool).stake(_user); IVirtualBalanceWrapper(pool.virtualBalance).stakeFor(_user, _amount); emit Deposited(_user, _pid, _amount); return true; } function withdrawFrozenTokens(uint256 _pid, uint256 _amount) public nonReentrant { require(_amount > 0, "!_amount"); PoolInfo storage pool = poolInfo[_pid]; frozenTokens[_pid][msg.sender] = frozenTokens[_pid][msg.sender].sub( _amount ); IOriginConvexRewardPool(pool.originCrvRewards).withdrawAndUnwrap( _amount, true ); IERC20(pool.lpToken).safeTransfer(msg.sender, _amount); } function withdrawFor( uint256 _pid, uint256 _amount, address _user, bool _frozenTokens ) public override onlyLendingMarket nonReentrant returns (bool) { PoolInfo storage pool = poolInfo[_pid]; if (_frozenTokens) { frozenTokens[_pid][_user] = frozenTokens[_pid][_user].add(_amount); } else { IOriginConvexRewardPool(pool.originCrvRewards).withdrawAndUnwrap( _amount, true ); IERC20(pool.lpToken).safeTransfer(_user, _amount); } if (IConvexRewardPool(pool.rewardCrvPool).earned(_user) > 0) { IConvexRewardPool(pool.rewardCrvPool).getReward(_user); } if (IConvexRewardPool(pool.rewardCvxPool).earned(_user) > 0) { IConvexRewardPool(pool.rewardCvxPool).getReward(_user); } IVirtualBalanceWrapper(pool.virtualBalance).withdrawFor(_user, _amount); IConvexRewardPool(pool.rewardCrvPool).withdraw(_user); IConvexRewardPool(pool.rewardCvxPool).withdraw(_user); emit Withdrawn(_user, _pid, _amount); return true; } function _removeLiquidity( address _lpToken, address _curveSwapAddress, uint256 _amount, int128 _coinId ) internal { if (metaPoolInfo[_lpToken].zapAddress != address(0)) { if (metaPoolInfo[_lpToken].isMetaFactory) { ICurveSwapV2(metaPoolInfo[_lpToken].zapAddress) .remove_liquidity_one_coin(_lpToken, _amount, _coinId, 0); emit RemoveLiquidity( _lpToken, _curveSwapAddress, _amount, _coinId ); return; } } ICurveSwapV2(_curveSwapAddress).remove_liquidity_one_coin( _amount, _coinId, 0 ); emit RemoveLiquidity(_lpToken, _curveSwapAddress, _amount, _coinId); } function liquidate( uint256 _pid, int128 _coinId, address _user, uint256 _amount ) external override onlyLendingMarket nonReentrant returns (address, uint256) { PoolInfo storage pool = poolInfo[_pid]; IOriginConvexRewardPool(pool.originCrvRewards).withdrawAndUnwrap( _amount, true ); IVirtualBalanceWrapper(pool.virtualBalance).withdrawFor(_user, _amount); if (IConvexRewardPool(pool.rewardCrvPool).earned(_user) > 0) { IConvexRewardPool(pool.rewardCrvPool).getReward(_user); } if (IConvexRewardPool(pool.rewardCvxPool).earned(_user) > 0) { IConvexRewardPool(pool.rewardCvxPool).getReward(_user); } IConvexRewardPool(pool.rewardCrvPool).withdraw(_user); IConvexRewardPool(pool.rewardCvxPool).withdraw(_user); IERC20(pool.lpToken).safeApprove(pool.curveSwapAddress, 0); IERC20(pool.lpToken).safeApprove(pool.curveSwapAddress, _amount); address underlyToken; if (metaPoolInfo[pool.lpToken].zapAddress != address(0)) { if ( metaPoolInfo[pool.lpToken].swapAddress == metaPoolInfo[pool.lpToken].basePoolAddress || (!metaPoolInfo[pool.lpToken].isMeta && !metaPoolInfo[pool.lpToken].isMetaFactory) || _coinId == 0 ) { underlyToken = _coins(pool.curveSwapAddress, _coinId); } else { underlyToken = _coins( metaPoolInfo[pool.lpToken].basePoolAddress, _coinId - 1 ); } } else { underlyToken = _coins(pool.curveSwapAddress, _coinId); } _removeLiquidity(pool.lpToken, pool.curveSwapAddress, _amount, _coinId); if (underlyToken == ZERO_ADDRESS) { uint256 totalAmount = address(this).balance; msg.sender.sendValue(totalAmount); return (ZERO_ADDRESS, totalAmount); } else { uint256 totalAmount = IERC20(underlyToken).balanceOf(address(this)); IERC20(underlyToken).safeTransfer(msg.sender, totalAmount); return (underlyToken, totalAmount); } } function getRewards(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; if (IConvexRewardPool(pool.rewardCrvPool).earned(msg.sender) > 0) { IConvexRewardPool(pool.rewardCrvPool).getReward(msg.sender); } if (IConvexRewardPool(pool.rewardCvxPool).earned(msg.sender) > 0) { IConvexRewardPool(pool.rewardCvxPool).getReward(msg.sender); } } function claimRewardToken(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IOriginConvexRewardPool(pool.originCrvRewards).getReward( address(this), true ); address rewardUnderlyToken = IOriginConvexRewardPool( pool.originCrvRewards ).rewardToken(); uint256 crvBalance = IERC20(rewardUnderlyToken).balanceOf( address(this) ); if (crvBalance > 0) { IERC20(rewardUnderlyToken).safeTransfer( pool.rewardCrvPool, crvBalance ); IConvexRewardPool(pool.rewardCrvPool).notifyRewardAmount( crvBalance ); } uint256 extraRewardsLength = IConvexRewardPool(pool.rewardCrvPool) .extraRewardsLength(); for (uint256 i = 0; i < extraRewardsLength; i++) { address currentExtraReward = IConvexRewardPool(pool.rewardCrvPool) .extraRewards(i); address originExtraRewardToken = IOriginConvexRewardPool( pool.originCrvRewards ).extraRewards(i); address extraRewardUnderlyToken = IOriginConvexVirtualBalanceRewardPool( originExtraRewardToken ).rewardToken(); IOriginConvexVirtualBalanceRewardPool(originExtraRewardToken) .getReward(address(this)); uint256 extraBalance = IERC20(extraRewardUnderlyToken).balanceOf( address(this) ); if (extraBalance > 0) { IERC20(extraRewardUnderlyToken).safeTransfer( currentExtraReward, extraBalance ); IConvexRewardPool(currentExtraReward).notifyRewardAmount( extraBalance ); } } /* cvx */ uint256 cvxBal = IERC20(rewardCvxToken).balanceOf(address(this)); if (cvxBal > 0) { IERC20(rewardCvxToken).safeTransfer(pool.rewardCvxPool, cvxBal); IConvexRewardPool(pool.rewardCvxPool).notifyRewardAmount(cvxBal); } emit ClaimRewardToken(_pid); } function claimAllRewardToken() public { for (uint256 i = 0; i < poolInfo.length; i++) { claimRewardToken(i); } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /* view functions */ function poolLength() external view returns (uint256) { return poolInfo.length; } function getPoolToken(uint256 _pid) external view override returns (address) { PoolInfo storage pool = poolInfo[_pid]; return pool.lpToken; } function getPoolZapAddress(address _lpToken) external view override returns (address) { return metaPoolInfo[_lpToken].zapAddress; } function _coins(address _swapAddress, int128 _coinId) internal view returns (address) { // curve v1 base pool address susd = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address sbtc = 0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714; address ren = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; if ( _swapAddress == susd || _swapAddress == sbtc || _swapAddress == ren ) { return ICurveSwapV2(_swapAddress).coins(_coinId); } return ICurveSwapV2(_swapAddress).coins(uint256(_coinId)); } function calculateTokenAmount( uint256 _pid, uint256 _tokens, int128 _curveCoinId ) external view override returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; if (metaPoolInfo[pool.lpToken].zapAddress != address(0)) { if (metaPoolInfo[pool.lpToken].isMetaFactory) { return ICurveSwapV2(metaPoolInfo[pool.lpToken].zapAddress) .calc_withdraw_one_coin( pool.curveSwapAddress, _tokens, _curveCoinId ); } return ICurveSwapV2(metaPoolInfo[pool.lpToken].zapAddress) .calc_withdraw_one_coin(_tokens, _curveCoinId); } return ICurveSwapV2(pool.curveSwapAddress).calc_withdraw_one_coin( _tokens, _curveCoinId ); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract LendFlareToken is Initializable, 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; uint256 public constant YEAR = 1 days * 365; uint256 public constant INITIAL_RATE = (274815283 * 10**18) / YEAR; // leading to 43% premine uint256 public constant RATE_REDUCTION_TIME = YEAR; uint256 public constant RATE_REDUCTION_COEFFICIENT = 1189207115002721024; // 2 ** (1/4) * 1e18 uint256 public constant RATE_DENOMINATOR = 10**18; uint256 public startEpochTime; uint256 public startEpochSupply; uint256 public miningEpoch; uint256 public rate; uint256 public version; address public multiSigUser; address public owner; address public minter; address public liquidityTransformer; bool public liquidity; event UpdateMiningParameters(uint256 time, uint256 rate, uint256 supply); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); event SetMinter(address minter); event SetOwner(address owner); event LiquidityTransformer( address indexed _from, address indexed _to, uint256 _value ); // @custom:oz-upgrades-unsafe-allow constructor constructor() public initializer {} function initialize(address _owner, address _multiSigUser) public initializer { _name = "LendFlare DAO Token"; _symbol = "LFT"; _decimals = 18; version = 1; owner = _owner; multiSigUser = _multiSigUser; startEpochTime = block.timestamp.sub(RATE_REDUCTION_TIME); miningEpoch = 0; rate = 0; startEpochSupply = 0; } modifier onlyOwner() { require(owner == msg.sender, "LendFlareToken: caller is not the owner"); _; } modifier onlyLiquidityTransformer() { require( liquidityTransformer == msg.sender, "LendFlareToken: caller is not the liquidityTransformer" ); _; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } function setLiquidityTransformer(address _v) public onlyOwner { require(_v != address(0), "!_v"); require(liquidityTransformer == address(0), "!liquidityTransformer"); liquidityTransformer = _v; uint256 supply = 909090909 * 10**18; _balances[liquidityTransformer] = supply; _totalSupply = _totalSupply.add(supply); startEpochSupply = startEpochSupply.add(supply); emit LiquidityTransformer(address(0), multiSigUser, supply); } function setLiquidityFinish() external onlyLiquidityTransformer { require(!liquidity, "!liquidity"); uint256 officialTeam = 90909090 * 10**18; uint256 merkleAirdrop = 30303030 * 10**18; uint256 earlyLiquidityReward = 151515151 * 10**18; uint256 community = 121212121 * 10**18; uint256 supply = officialTeam .add(merkleAirdrop) .add(earlyLiquidityReward) .add(community); _balances[multiSigUser] = supply; _totalSupply = _totalSupply.add(supply); startEpochSupply = startEpochSupply.add(supply); liquidity = true; emit Transfer(address(0), multiSigUser, officialTeam); emit Transfer(address(0), multiSigUser, merkleAirdrop); emit Transfer(address(0), multiSigUser, earlyLiquidityReward); emit Transfer(address(0), multiSigUser, community); } function _updateMiningParameters() internal { startEpochTime = startEpochTime.add(RATE_REDUCTION_TIME); miningEpoch++; if (rate == 0) { rate = INITIAL_RATE; } else { startEpochSupply = startEpochSupply.add( rate.mul(RATE_REDUCTION_TIME) ); rate = rate.mul(RATE_DENOMINATOR).div(RATE_REDUCTION_COEFFICIENT); } emit UpdateMiningParameters(block.timestamp, rate, startEpochSupply); } function updateMiningParameters() external { require( block.timestamp >= startEpochTime.add(RATE_REDUCTION_TIME), "too soon!" ); _updateMiningParameters(); } function startEpochTimeWrite() external returns (uint256) { if (block.timestamp >= startEpochTime.add(RATE_REDUCTION_TIME)) { _updateMiningParameters(); } return startEpochTime; } function futureEpochTimeWrite() external returns (uint256) { if (block.timestamp >= startEpochTime.add(RATE_REDUCTION_TIME)) { _updateMiningParameters(); } return startEpochTime.add(RATE_REDUCTION_TIME); } function availableSupply() public view returns (uint256) { return startEpochSupply.add(block.timestamp.sub(startEpochTime).mul(rate)); } function setMinter(address _minter) public onlyOwner { require(_minter != address(0), "!_minter"); minter = _minter; emit SetMinter(_minter); } function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address user, address spender) public view virtual override returns (uint256) { return _allowances[user][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub( amount, "transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub( subtractedValue, "decreased allowance below zero" ) ); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "transfer from the zero address"); require(recipient != address(0), "transfer to the zero address"); _balances[sender] = _balances[sender].sub( amount, "transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function mint(address account, uint256 amount) public returns (bool) { require(msg.sender == minter, "!minter"); require(account != address(0), "mint to the zero address"); if (!liquidity) return false; if (block.timestamp >= startEpochTime.add(RATE_REDUCTION_TIME)) { _updateMiningParameters(); } _totalSupply = _totalSupply.add(amount); require( _totalSupply <= availableSupply(), "exceeds allowable mint amount" ); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) public returns (bool) { _balances[msg.sender] = _balances[msg.sender].sub( amount, "burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(msg.sender, address(0), amount); } function _approve( address user, address spender, uint256 amount ) internal virtual { require(user != address(0), "approve from the zero address"); require(spender != address(0), "approve to the zero address"); _allowances[user][spender] = amount; emit Approval(user, spender, amount); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Timelock { using SafeMath for uint256; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 1 days; uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; mapping(bytes32 => bool) public queuedTransactions; constructor(address admin_, uint256 delay_) public { admin = admin_; _setDelay(delay_); } function _setDelay(uint256 delay_) internal { require( delay_ >= MINIMUM_DELAY, "Timelock::_setDelay: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "Timelock::_setDelay: Delay must not exceed maximum delay." ); delay = delay_; emit NewDelay(delay); } function setDelay(uint256 delay_) public { require( msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock." ); _setDelay(delay_); } function acceptAdmin() public { require( msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin." ); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require( msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock." ); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public returns (bytes32) { require( msg.sender == admin, "Timelock::queueTransaction: Call must come from admin." ); require( eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay." ); bytes32 txHash = keccak256( abi.encode(target, value, signature, data, eta) ); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public { require( msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin." ); bytes32 txHash = keccak256( abi.encode(target, value, signature, data, eta) ); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public payable returns (bytes memory) { require( msg.sender == admin, "Timelock::executeTransaction: Call must come from admin." ); bytes32 txHash = keccak256( abi.encode(target, value, signature, data, eta) ); require( queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued." ); require( getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock." ); require( getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale." ); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked( bytes4(keccak256(bytes(signature))), data ); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}( callData ); require(success, _getRevertMsg(returnData)); // require( // success, // "Timelock::executeTransaction: Transaction execution reverted." // ); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract LendingSponsor is ReentrancyGuard { using Address for address payable; using SafeMath for uint256; enum LendingInfoState { NONE, CLOSED } struct LendingInfo { address user; uint256 amount; LendingInfoState state; } address public lendingMarket; uint256 public totalSupply; address public owner; mapping(bytes32 => LendingInfo) public lendingInfos; event AddSponsor(bytes32 sponsor, uint256 amount); event PayFee(bytes32 sponsor, address user, uint256 sponsorAmount); modifier onlyLendingMarket() { require( lendingMarket == msg.sender, "LendingSponsor: caller is not the lendingMarket" ); _; } modifier onlyOwner() { require(owner == msg.sender, "LendingSponsor: caller is not the owner"); _; } constructor() public { owner = msg.sender; } function setLendingMarket(address _v) external onlyOwner { require(_v != address(0), "!_v"); lendingMarket = _v; owner = address(0); } function payFee(bytes32 _lendingId, address payable _user) public onlyLendingMarket nonReentrant { LendingInfo storage lendingInfo = lendingInfos[_lendingId]; if (lendingInfo.state == LendingInfoState.NONE) { lendingInfo.state = LendingInfoState.CLOSED; _user.sendValue(lendingInfo.amount); totalSupply = totalSupply.sub(lendingInfo.amount); emit PayFee(_lendingId, _user, lendingInfo.amount); } } function addSponsor(bytes32 _lendingId, address _user) public payable onlyLendingMarket nonReentrant { lendingInfos[_lendingId] = LendingInfo({ user: _user, amount: msg.value, state: LendingInfoState.NONE }); totalSupply = totalSupply.add(msg.value); emit AddSponsor(_lendingId, msg.value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./UpgradeableProxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external virtual ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity 0.6.12; import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol"; contract LendFlareProxy is TransparentUpgradeableProxy { constructor( address logic, address admin, bytes memory data ) public TransparentUpgradeableProxy(logic, admin, data) {} } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; interface ILiquidityGauge { function updateReward(address _for) external; function totalAccrued(address _for) external view returns (uint256); } interface ILendFlareToken { function mint(address _for, uint256 amount) external; } contract LendFlareTokenMinter is ReentrancyGuard { using SafeMath for uint256; address public token; address public supplyPoolExtraRewardFactory; uint256 public launchTime; mapping(address => mapping(address => uint256)) public minted; // user -> gauge -> value event Minted(address user, address gauge, uint256 amount); constructor( address _token, address _supplyPoolExtraRewardFactory, uint256 _launchTime ) public { require(_launchTime > block.timestamp, "!_launchTime"); launchTime = _launchTime; token = _token; supplyPoolExtraRewardFactory = _supplyPoolExtraRewardFactory; } function _mintFor(address _gauge, address _for) internal { if (block.timestamp >= launchTime) { ILiquidityGauge(_gauge).updateReward(_for); uint256 totalMint = ILiquidityGauge(_gauge).totalAccrued(_for); uint256 toMint = totalMint.sub(minted[_for][_gauge]); if (toMint > 0) { ILendFlareToken(token).mint(_for, toMint); minted[_for][_gauge] = totalMint; emit Minted(_for, _gauge, totalMint); } } } function mintFor(address _gauge, address _for) public nonReentrant { require( msg.sender == supplyPoolExtraRewardFactory, "LendFlareTokenMinter: !authorized mintFor" ); _mintFor(_gauge, _for); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract LendFlareGaugeModel { using SafeMath for uint256; struct GaugeModel { address gauge; uint256 weight; bool shutdown; } address[] public gauges; address public owner; address public supplyExtraReward; mapping(address => GaugeModel) public gaugeWeights; event AddGaguge(address indexed gauge, uint256 weight); event ToggleGauge(address indexed gauge, bool enabled); event UpdateGaugeWeight(address indexed gauge, uint256 weight); event SetOwner(address owner); modifier onlyOwner() { require( owner == msg.sender, "LendFlareGaugeModel: caller is not the owner" ); _; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } constructor() public { owner = msg.sender; } function setSupplyExtraReward(address _v) public onlyOwner { require(_v != address(0), "!_v"); supplyExtraReward = _v; } // default = 100000000000000000000 weight(%) = 100000000000000000000 * 1e18/ total * 100 function addGauge(address _gauge, uint256 _weight) public { require( msg.sender == supplyExtraReward, "LendFlareGaugeModel: !authorized addGauge" ); gauges.push(_gauge); gaugeWeights[_gauge] = GaugeModel({ gauge: _gauge, weight: _weight, shutdown: false }); } function updateGaugeWeight(address _gauge, uint256 _newWeight) public onlyOwner { require(_gauge != address(0), "LendFlareGaugeModel:: !_gauge"); require( gaugeWeights[_gauge].gauge == _gauge, "LendFlareGaugeModel: !found" ); gaugeWeights[_gauge].weight = _newWeight; emit UpdateGaugeWeight(_gauge, gaugeWeights[_gauge].weight); } function toggleGauge(address _gauge, bool _state) public { require( msg.sender == supplyExtraReward, "LendFlareGaugeModel: !authorized toggleGauge" ); gaugeWeights[_gauge].shutdown = _state; emit ToggleGauge(_gauge, _state); } function getGaugeWeightShare(address _gauge) public view returns (uint256) { uint256 totalWeight; for (uint256 i = 0; i < gauges.length; i++) { if (!gaugeWeights[gauges[i]].shutdown) { totalWeight = totalWeight.add(gaugeWeights[gauges[i]].weight); } } return gaugeWeights[_gauge].weight.mul(1e18).div(totalWeight); } function gaugesLength() public view returns (uint256) { return gauges.length; } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract VirtualBalanceWrapper { using SafeMath for uint256; address public owner; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(address _owner) public { owner = _owner; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address _for) public view returns (uint256) { return _balances[_for]; } function stakeFor(address _for, uint256 _amount) public returns (bool) { require( msg.sender == owner, "VirtualBalanceWrapper: !authorized stakeFor" ); require(_amount > 0, "VirtualBalanceWrapper: !_amount"); _totalSupply = _totalSupply.add(_amount); _balances[_for] = _balances[_for].add(_amount); return true; } function withdrawFor(address _for, uint256 _amount) public returns (bool) { require( msg.sender == owner, "VirtualBalanceWrapper: !authorized withdrawFor" ); require(_amount > 0, "VirtualBalanceWrapper: !_amount"); _totalSupply = _totalSupply.sub(_amount); _balances[_for] = _balances[_for].sub(_amount); return true; } } contract VirtualBalanceWrapperFactory { event NewOwner(address indexed sender, address operator); event RemoveOwner(address indexed sender, address operator); mapping(address => bool) private owners; modifier onlyOwners() { require(isOwner(msg.sender), "vbw: caller is not an owner onlyOwners"); _; } constructor() public { owners[msg.sender] = true; } function addOwner(address _newOwner) public onlyOwners { require(!isOwner(_newOwner), "vbw: address is already owner addOwner"); owners[_newOwner] = true; emit NewOwner(msg.sender, _newOwner); } function addOwners(address[] calldata _newOwners) external onlyOwners { for (uint256 i = 0; i < _newOwners.length; i++) { addOwner(_newOwners[i]); } } function removeOwner(address _owner) external onlyOwners { require(isOwner(_owner), "vbw: address is not owner removeOwner"); owners[_owner] = false; emit RemoveOwner(msg.sender, _owner); } function isOwner(address _owner) public view returns (bool) { return owners[_owner]; } function createWrapper(address _owner) public onlyOwners returns (address) { return address(new VirtualBalanceWrapper(_owner)); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract MerkleAirdrop { using SafeERC20 for IERC20; struct Layer { address token; uint96 startTime; uint96 endTime; mapping(uint256 => uint256) claimed; } mapping(bytes32 => Layer) public layers; address public owner; event Claimed(address account, address token, uint256 amount); event SetOwner(address owner); modifier onlyOwner() { require(owner == msg.sender, "caller is not the owner"); _; } function setOwner(address _owner) public onlyOwner { owner = _owner; emit SetOwner(_owner); } constructor() public { owner = msg.sender; } function newlayer( bytes32 merkleRoot, address token, uint96 startTime, uint96 endTime ) external onlyOwner { require( layers[merkleRoot].token == address(0), "merkleRoot already register" ); require(merkleRoot != bytes32(0), "empty root"); require(token != address(0), "empty token"); require(startTime < endTime, "wrong dates"); Layer storage _layer = layers[merkleRoot]; _layer.token = token; _layer.startTime = startTime; _layer.endTime = endTime; } function isClaimed(bytes32 merkleRoot, uint256 index) public view returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = layers[merkleRoot].claimed[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(bytes32 merkleRoot, uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; layers[merkleRoot].claimed[claimedWordIndex] = layers[merkleRoot].claimed[claimedWordIndex] | (1 << claimedBitIndex); } function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProofs ) external { bytes32 leaf = keccak256(abi.encodePacked(index, account, amount)); bytes32 merkleRoot = processProof(merkleProofs, leaf); require(layers[merkleRoot].token != address(0), "empty token"); require( layers[merkleRoot].startTime < block.timestamp && layers[merkleRoot].endTime >= block.timestamp, "out of time" ); require(!isClaimed(merkleRoot, index), "already claimed"); _setClaimed(merkleRoot, index); IERC20(layers[merkleRoot].token).safeTransfer(account, amount); emit Claimed(account, address(layers[merkleRoot].token), amount); } function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) public pure returns (bool) { return processProof(proof, leaf) == root; } 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 = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } } return computedHash; } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); } interface ILendFlareToken is IERC20 { function setLiquidityFinish() external; } contract LiquidityTransformer is ReentrancyGuard { using Address for address payable; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; ILendFlareToken public lendflareToken; address public uniswapPair; IUniswapV2Router02 public constant uniswapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address payable teamAddress; uint256 public constant FEE_DENOMINATOR = 10; uint256 public constant liquifyTokens = 909090909 * 1e18; uint256 public investmentTime; uint256 public minInvest; uint256 public launchTime; struct Globals { uint256 totalUsers; uint256 totalBuys; uint256 transferredUsers; uint256 totalWeiContributed; bool liquidity; uint256 endTimeAt; } Globals public globals; mapping(address => uint256) public investorBalances; mapping(address => uint256[2]) investorHistory; event UniSwapResult( uint256 amountToken, uint256 amountETH, uint256 liquidity, uint256 endTimeAt ); modifier afterUniswapTransfer() { require(globals.liquidity == true, "Forward liquidity first"); _; } constructor( address _lendflareToken, address payable _teamAddress, uint256 _launchTime ) public { require(_launchTime > block.timestamp, "!_launchTime"); launchTime = _launchTime; lendflareToken = ILendFlareToken(_lendflareToken); teamAddress = _teamAddress; minInvest = 0.1 ether; investmentTime = 7 days; } function createPair() external { require(address(uniswapPair) == address(0), "!uniswapPair"); uniswapPair = address( IUniswapV2Factory(factory()).createPair( WETH(), address(lendflareToken) ) ); } receive() external payable { require( msg.sender == address(uniswapRouter) || msg.sender == teamAddress, "Direct deposits disabled" ); } function reserve() external payable { _reserve(msg.sender, msg.value); } function reserveWithToken(address _tokenAddress, uint256 _tokenAmount) external { IERC20 token = IERC20(_tokenAddress); token.safeTransferFrom(msg.sender, address(this), _tokenAmount); token.approve(address(uniswapRouter), _tokenAmount); address[] memory _path = preparePath(_tokenAddress); uint256[] memory amounts = uniswapRouter.swapExactTokensForETH( _tokenAmount, minInvest, _path, address(this), block.timestamp ); _reserve(msg.sender, amounts[1]); } function _reserve(address _senderAddress, uint256 _senderValue) internal { require(block.timestamp >= launchTime, "Not started"); require( block.timestamp <= launchTime.add(investmentTime), "IDO has ended" ); require(globals.liquidity == false, "!globals.liquidity"); require(_senderValue >= minInvest, "Investment below minimum"); if (investorBalances[_senderAddress] == 0) { globals.totalUsers++; } investorBalances[_senderAddress] = investorBalances[_senderAddress].add( _senderValue ); globals.totalWeiContributed = globals.totalWeiContributed.add( _senderValue ); globals.totalBuys++; } function forwardLiquidity() external nonReentrant { require(msg.sender == tx.origin, "!EOA"); require(globals.liquidity == false, "!globals.liquidity"); require( block.timestamp > launchTime.add(investmentTime), "Not over yet" ); uint256 _etherFee = globals.totalWeiContributed.div(FEE_DENOMINATOR); uint256 _balance = globals.totalWeiContributed.sub(_etherFee); teamAddress.sendValue(_etherFee); uint256 half = liquifyTokens.div(2); uint256 _lendflareTokenFee = half.div(FEE_DENOMINATOR); IERC20(lendflareToken).safeTransfer(teamAddress, _lendflareTokenFee); lendflareToken.approve( address(uniswapRouter), half.sub(_lendflareTokenFee) ); ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) = uniswapRouter.addLiquidityETH{value: _balance}( address(lendflareToken), half.sub(_lendflareTokenFee), 0, 0, address(0x0), block.timestamp ); globals.liquidity = true; globals.endTimeAt = block.timestamp; lendflareToken.setLiquidityFinish(); emit UniSwapResult( amountToken, amountETH, liquidity, globals.endTimeAt ); } function getMyTokens() external afterUniswapTransfer nonReentrant { require(globals.liquidity, "!globals.liquidity"); require(investorBalances[msg.sender] > 0, "!balance"); uint256 myTokens = checkMyTokens(msg.sender); investorHistory[msg.sender][0] = investorBalances[msg.sender]; investorHistory[msg.sender][1] = myTokens; investorBalances[msg.sender] = 0; IERC20(lendflareToken).safeTransfer(msg.sender, myTokens); globals.transferredUsers++; if (globals.transferredUsers == globals.totalUsers) { uint256 surplusBalance = IERC20(lendflareToken).balanceOf( address(this) ); if (surplusBalance > 0) { IERC20(lendflareToken).safeTransfer( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, surplusBalance ); } } } /* view functions */ function WETH() public pure returns (address) { return IUniswapV2Router02(uniswapRouter).WETH(); } function checkMyTokens(address _sender) public view returns (uint256) { if ( globals.totalWeiContributed == 0 || investorBalances[_sender] == 0 ) { return 0; } uint256 half = liquifyTokens.div(2); uint256 otherHalf = liquifyTokens.sub(half); uint256 percent = investorBalances[_sender].mul(100e18).div( globals.totalWeiContributed ); uint256 myTokens = otherHalf.mul(percent).div(100e18); return myTokens; } function factory() public pure returns (address) { return IUniswapV2Router02(uniswapRouter).factory(); } function getInvestorHistory(address _sender) public view returns (uint256[2] memory) { return investorHistory[_sender]; } function preparePath(address _tokenAddress) internal pure returns (address[] memory _path) { _path = new address[](2); _path[0] = _tokenAddress; _path[1] = WETH(); } } // SPDX-License-Identifier: UNLICENSED /* _ _ _____ _ | | ___ _ __ __| | | ___| | | __ _ _ __ ___ | | / _ \ | '_ \ / _` | | |_ | | / _` | | '__| / _ \ | |___ | __/ | | | | | (_| | | _| | | | (_| | | | | __/ |_____| \___| |_| |_| \__,_| |_| |_| \__,_| |_| \___| LendFlare.finance */ pragma solidity =0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; contract LendFlareTokenLocker is ReentrancyGuard { using SafeERC20 for IERC20; address public owner; address public token; uint256 public start_time; uint256 public end_time; mapping(address => uint256) public initial_locked; mapping(address => uint256) public total_claimed; mapping(address => uint256) public disabled_at; uint256 public initial_locked_supply; uint256 public unallocated_supply; event Fund(address indexed recipient, uint256 amount); event Claim(address indexed recipient, uint256 amount); event ToggleDisable(address recipient, bool disabled); event SetOwner(address owner); constructor( address _owner, address _token, uint256 _start_time, uint256 _end_time ) public { require( _start_time >= block.timestamp, "_start_time >= block.timestamp" ); require(_end_time > _start_time, "_end_time > _start_time"); owner = _owner; token = _token; start_time = _start_time; end_time = _end_time; } function setOwner(address _owner) external { require( msg.sender == owner, "LendFlareTokenLocker: !authorized setOwner" ); owner = _owner; emit SetOwner(_owner); } function addTokens(uint256 _amount) public { require( msg.sender == owner, "LendFlareTokenLocker: !authorized addTokens" ); IERC20(token).safeTransferFrom(msg.sender, address(this), _amount); unallocated_supply += _amount; } function fund(address[] memory _recipients, uint256[] memory _amounts) public { require(msg.sender == owner, "LendFlareTokenLocker: !authorized fund"); require( _recipients.length == _amounts.length, "_recipients != _amounts" ); uint256 _total_amount; for (uint256 i = 0; i < _amounts.length; i++) { uint256 amount = _amounts[i]; address recipient = _recipients[i]; if (recipient == address(0)) { break; } _total_amount += amount; initial_locked[recipient] += amount; emit Fund(recipient, amount); } initial_locked_supply += _total_amount; unallocated_supply -= _total_amount; } function toggleDisable(address _recipient) public { require( msg.sender == owner, "LendFlareTokenLocker: !authorized toggleDisable" ); bool is_enabled = disabled_at[_recipient] == 0; if (is_enabled) { disabled_at[_recipient] = block.timestamp; } else { disabled_at[_recipient] = 0; } emit ToggleDisable(_recipient, is_enabled); } function claim() public nonReentrant { address recipient = msg.sender; uint256 t = disabled_at[recipient]; if (t == 0) { t = block.timestamp; } uint256 claimable = _totalVestedOf(recipient, t) - total_claimed[recipient]; total_claimed[recipient] += claimable; IERC20(token).safeTransfer(recipient, claimable); emit Claim(recipient, claimable); } function _totalVestedOf(address _recipient, uint256 _time) internal view returns (uint256) { if (_time == 0) _time = block.timestamp; uint256 locked = initial_locked[_recipient]; if (_time < start_time) { return 0; } return min( (locked * (_time - start_time)) / (end_time - start_time), locked ); } function vestedSupply() public view returns (uint256) { uint256 locked = initial_locked_supply; if (block.timestamp < start_time) { return 0; } return min( (locked * (block.timestamp - start_time)) / (end_time - start_time), locked ); } function lockedSupply() public view returns (uint256) { return initial_locked_supply - vestedSupply(); } function availableOf(address _recipient) public view returns (uint256) { uint256 t = disabled_at[_recipient]; if (t == 0) { t = block.timestamp; } return _totalVestedOf(_recipient, t) - total_claimed[_recipient]; } function lockedOf(address _recipient) public view returns (uint256) { return initial_locked[_recipient] - _totalVestedOf(_recipient, block.timestamp); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract LendFlareTokenLockerFactory { uint256 public totalLockers; mapping(uint256 => address) public lockers; address public owner; event CreateLocker( uint256 indexed uniqueId, address indexed locker, string description ); constructor() public { owner = msg.sender; } function setOwner(address _owner) external { require( msg.sender == owner, "LendFlareTokenLockerFactory: !authorized setOwner" ); owner = _owner; } function createLocker( uint256 _uniqueId, address _token, uint256 _start_time, uint256 _end_time, address _owner, string calldata description ) external returns (address) { require( msg.sender == owner, "LendFlareTokenLockerFactory: !authorized createLocker" ); require(lockers[_uniqueId] == address(0), "!_uniqueId"); LendFlareTokenLocker locker = new LendFlareTokenLocker( _owner, _token, _start_time, _end_time ); lockers[_uniqueId] = address(locker); totalLockers++; emit CreateLocker(_uniqueId, address(locker), description); } }
default weight = 100 1e18
function createPool( uint256 _pid, address _underlyToken, address _virtualBalance, bool _isErc20 ) internal { address lendflareMinter = ILendflareToken(lendflareToken).minter(); require(lendflareMinter != address(0), "!lendflareMinter"); address poolGauge = ISupplyPoolGaugeFactory(supplyPoolGaugeFactory) .createGauge( _virtualBalance, lendflareToken, lendflareVotingEscrow, lendflareGaugeModel, lendflareMinter ); ILendflareGaugeModel(lendflareGaugeModel).addGauge(poolGauge, 100e18); address rewardVeLendFlarePool; if (_isErc20) { rewardVeLendFlarePool = ISupplyRewardFactory(supplyRewardFactory) .createReward( _underlyToken, lendflareVotingEscrow, address(this) ); rewardVeLendFlarePool = ISupplyRewardFactory(supplyRewardFactory) .createReward(address(0), lendflareVotingEscrow, address(this)); } ILendFlareVotingEscrow(lendflareVotingEscrow).addRewardPool( rewardVeLendFlarePool ); IBaseReward(rewardVeLendFlarePool).addOwner(lendflareVotingEscrow); veLendFlarePool[_pid] = rewardVeLendFlarePool; gaugePool[_pid] = poolGauge; }
6,233,054
// SPDX-License-Identifier: GPL-3.0 pragma solidity =0.8.10; import "./IERC20.sol"; import "./IUniswapV2Router02.sol"; import "./IUniswapV2Factory.sol"; import "./IUniswapV2Pair.sol"; import "./IHyperDeFi.sol"; import "./IHyperDeFiBuffer.sol"; import "./IHyperDeFiIDO.sol"; import "./Ownable.sol"; import "./Math.sol"; import "./HyperDeFiTokenMetadata.sol"; /** * @dev DeFi Token */ contract HyperDeFiToken is Ownable, IHyperDeFi, HyperDeFiTokenMetadata { using Math for uint256; struct Percentage { uint8 farm; uint8 airdrop; uint8 fomo; uint8 liquidity; uint8 fund; uint8 destroy; } struct Snap { uint256 totalSupply; uint256 totalTax; } bool private _swapLock; uint256 internal _totalSupply; uint256 internal _distributed; uint256 internal _totalFarm; uint256 internal _totalUsername; uint256 internal _fomoTimestamp; address[] internal _flats; address[] internal _slots; address[] internal _funds; address[] internal _holders; // Resources IHyperDeFiIDO internal constant IDO = IHyperDeFiIDO(ADDRESS_IDO); IHyperDeFiBuffer internal constant BUFFER = IHyperDeFiBuffer(ADDRESS_BUFFER); IUniswapV2Router02 internal constant DEX = IUniswapV2Router02(ADDRESS_DEX); IUniswapV2Factory internal immutable DEX_FACTORY; IUniswapV2Pair internal immutable DEX_PAIR; IERC20 internal immutable WRAP; // uint256 internal _initPrice; uint256 internal _timestampLiquidityCreated; address internal _fomoNextAccount; // tax Percentage internal TAKER_TAX = Percentage(3, 1, 2, 5, 1, 3); Percentage internal MAKER_TAX = Percentage(3, 1, 1, 4, 1, 0); Percentage internal WHALE_TAX = Percentage(3, 1, 1, 5, 1, 19); Percentage internal ROBBER_TAX = Percentage(3, 1, 1, 5, 1, 74); mapping (address => uint256) internal _balance; mapping (address => uint256) internal _totalHarvest; mapping (address => uint256) internal _totalFarmSnap; mapping (address => string) internal _username; mapping (address => bool) internal _usernamed; mapping (string => address) internal _username2address; mapping (address => uint256) internal _coupon; mapping (uint256 => address) internal _inviter; mapping (address => uint256) internal _couponUsed; mapping (address => uint256) internal _visitors; mapping (address => bool) internal _isFlat; mapping (address => bool) internal _isSlot; mapping (address => bool) internal _isFund; mapping (address => bool) internal _isHolder; mapping (address => mapping (address => uint256)) internal _allowances; // enum enum TX_TYPE {MINT, HARVEST, FLAT, TAKER, MAKER, WHALE, ROBBER} // events event TX(uint8 indexed txType, address indexed sender, address indexed recipient, uint256 amount, uint256 txAmount); event SlotRegistered(address account); event UsernameSet(address indexed account, string username); event CouponVisitor(address inviter, address visitor); event Airdrop(address indexed account, uint256 amount); event Bonus(address indexed account, uint256 amount); event Fund(address indexed account, uint256 amount); // modifier withSwapLock { _swapLock = true; _; _swapLock = false; } // constructor () { WRAP = IERC20(DEX.WETH()); DEX_FACTORY = IUniswapV2Factory(DEX.factory()); DEX_PAIR = IUniswapV2Pair(DEX_FACTORY.createPair(address(WRAP), address(this))); _registerFund(FOMO); _registerFund(BLACK_HOLE); _registerFund(address(BUFFER)); _registerFund(address(IDO)); _registerFund(address(this)); _registerFund(_msgSender()); _mint(BLACK_HOLE, BURN_AMOUNT); _mint(address(IDO), IDO_AMOUNT); _isHolder[owner()] = true; _holders.push(owner()); } function getIDOConfigs() public pure returns ( uint256 IDOAmount, uint256 IDODepositCap, uint256 IDODepositMax, uint32 IDOTimestampFrom, uint32 IDOTimestampTo, address buffer ) { IDOAmount = IDO_AMOUNT; IDODepositCap = IDO_DEPOSIT_CAP; IDODepositMax = IDO_DEPOSIT_MAX; IDOTimestampFrom = IDO_TIMESTAMP_FROM; IDOTimestampTo = IDO_TIMESTAMP_TO; buffer = ADDRESS_BUFFER; } function getBufferConfigs() public pure returns ( address dex, address usd ) { dex = ADDRESS_DEX; usd = ADDRESS_USD; } function isInitialLiquidityCreated() public view returns (bool) { return 0 < _timestampLiquidityCreated; } /** * @dev Set username for `_msgSender()` */ function setUsername(string calldata value) external { require(0 < balanceOf(_msgSender()) || IDO.isFounder(_msgSender()), "HyperDeFi: balance is zero"); require(address(0) == _username2address[value], "HyperDeFi: username is already benn taken"); require(!_usernamed[_msgSender()], "HyperDeFi: username cannot be changed"); _username[_msgSender()] = value; _usernamed[_msgSender()] = true; _username2address[value] = _msgSender(); _totalUsername++; emit UsernameSet(_msgSender(), value); _mayAutoSwapIntoLiquidity(); } /** * @dev Generate coupon for `_msgSender()` */ function genConpon() external { require(0 < balanceOf(_msgSender()) || IDO.isFounder(_msgSender()), "HyperDeFi Conpon: balance is zero"); require(_coupon[_msgSender()] == 0, "HyperDeFi Conpon: already generated"); uint256 coupon = uint256(keccak256(abi.encode(blockhash(block.number - 1), _msgSender()))) % type(uint32).max; require(0 < coupon, "HyperDeFi Conpon: invalid code, please retry"); _coupon[_msgSender()] = coupon; _inviter[coupon] = _msgSender(); _mayAutoSwapIntoLiquidity(); } /** * @dev Set coupon for `_msgSender()` */ function useCoupon(uint256 coupon) external { address inviter = _inviter[coupon]; require(isValidCouponForAccount(coupon, _msgSender()), "HyperDeFi Coupon: invalid"); _couponUsed[_msgSender()] = coupon; _visitors[inviter]++; emit CouponVisitor(inviter, _msgSender()); _mayAutoSwapIntoLiquidity(); } /** * @dev Returns `true` if `coupon` is valid for `account` */ function isValidCouponForAccount(uint256 coupon, address account) public view returns (bool) { address inviter = _inviter[coupon]; if (inviter == address(0)) return false; for (uint8 i = 1; i < BONUS.length; i++) { if (inviter == account) return false; inviter = _inviter[_couponUsed[inviter]]; if (inviter == address(0)) return true; } return true; } /** * @dev Pay TAX */ function payFee(uint256 farm, uint256 airdrop, uint256 fomo, uint256 liquidity, uint256 fund, uint256 destroy) public returns (bool) { uint256 amount = farm + airdrop + fomo + liquidity + fund + destroy; require(amount > 0, "HyperDeFi: fee amount is zero"); require(amount <= balanceOf(_msgSender()), "HyperDeFi: fee amount exceeds balance"); unchecked { _balance[_msgSender()] -= amount; } if (0 < farm) _payFarm( _msgSender(), farm); if (0 < airdrop) _payAirdrop( _msgSender(), airdrop, _generateRandom(tx.origin)); if (0 < fomo) _payFomo( _msgSender(), fomo); if (0 < liquidity) _payLiquidity(_msgSender(), liquidity); if (0 < fund) _payFund( _msgSender(), fund); if (0 < destroy) _payDestroy( _msgSender(), destroy); _mayAutoSwapIntoLiquidity(); return true; } /** * @dev Pay TAX from `sender` */ function payFeeFrom(address sender, uint256 farm, uint256 airdrop, uint256 fomo, uint256 liquidity, uint256 fund, uint256 destroy) public returns (bool) { uint256 amount = farm + airdrop + fomo + liquidity + fund + destroy; require(amount > 0, "HyperDeFi: fee amount is zero"); require(amount <= balanceOf(sender), "HyperDeFi: fee amount exceeds balance"); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "HyperDeFi: fee amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); _balance[sender] -= amount; } if (0 < farm) _payFarm( sender, farm); if (0 < airdrop) _payAirdrop( sender, airdrop, _generateRandom(tx.origin)); if (0 < fomo) _payFomo( sender, fomo); if (0 < liquidity) _payLiquidity(sender, liquidity); if (0 < fund) _payFund( sender, fund); if (0 < destroy) _payDestroy( sender, destroy); _mayAutoSwapIntoLiquidity(); return true; } function harvestOf(address account) public view returns (uint256) { if (_totalFarm <= _totalFarmSnap[account]) return 0; // never happens uint256 harvest = _balance[account] * (_totalFarm - _totalFarmSnap[account]) / _totalSupply; return harvest.min(balanceOf(FARM)); } function takeHarvest() public returns (bool) { _takeHarvest(_msgSender()); _mayAutoSwapIntoLiquidity(); return true; } /** * @dev Register a slot for DApp */ function registerSlot(address account) public onlyOwner { require(!_isSlot[account], "The slot is already exist"); require(!_isHolder[account], "The holder is already exist"); _isSlot[account] = true; _isFlat[account] = true; _slots.push(account); _flats.push(account); emit SlotRegistered(account); _mayAutoSwapIntoLiquidity(); } // --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- ERC20 /** * @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 _balance[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { if (BLACK_HOLE == recipient || address(this) == recipient) { _burn(_msgSender(), amount); return true; } _transfer(_msgSender(), recipient, amount); return true; } /** * @dev Create initial liquidity */ function createInitLiquidity() public payable returns (bool) { require(_msgSender() == address(IDO), "HyperDeFi: caller is not the IDO contract"); require(0 == _timestampLiquidityCreated, "HyperDeFi: initial liquidity has been created"); _initPrice = address(this).balance * 10 ** _decimals / INIT_LIQUIDITY; _mint(address(this), INIT_LIQUIDITY); _approve(address(this), ADDRESS_DEX, type(uint256).max); DEX.addLiquidityETH{value: address(this).balance}( address(this), INIT_LIQUIDITY, 0, 0, BLACK_HOLE, block.timestamp ); _timestampLiquidityCreated = block.timestamp; return true; } /** * @dev Burn */ function burn(uint256 amount) public returns (bool) { _burn(_msgSender(), amount); _mayAutoSwapIntoLiquidity(); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); _mayAutoSwapIntoLiquidity(); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } _transfer(sender, recipient, amount); return true; } /** * @dev Burn from `sender` */ function burnFrom(address sender, uint256 amount) public returns (bool) { uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } _burn(sender, amount); _mayAutoSwapIntoLiquidity(); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); _mayAutoSwapIntoLiquidity(); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } _mayAutoSwapIntoLiquidity(); return true; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { 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 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) private { require(account != address(0), "ERC20: mint to the zero address"); require(TOTAL_SUPPLY_CAP >= _totalSupply + amount, "ERC20: cap exceeded"); _totalSupply += amount; _balance[account] += amount; emit Transfer(address(0), account, amount); emit TX(uint8(TX_TYPE.MINT), address(0), account, amount, amount); } /** * @dev Destroys `amount` tokens from `account` to black-hole. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); require(_totalSupply >= amount, "ERC20: burn amount exceeds total supply"); require(_balance[account] >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balance[account] -= amount; _balance[BLACK_HOLE] += amount; } emit Transfer(account, BLACK_HOLE, amount); } // --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- ERC20 <END> function _priceToken2WRAP() internal view returns (uint256 price) { uint256 pairTokenAmount = balanceOf(address(DEX_PAIR)); if (0 < pairTokenAmount) { return BUFFER.priceToken2WRAP(); } else { return IDO.priceToken2WRAP(); } } function _priceToken2USD() internal view returns (uint256 price) { uint256 pairTokenAmount = balanceOf(address(DEX_PAIR)); if (0 < pairTokenAmount) { return BUFFER.priceToken2USD(); } else { return IDO.priceToken2USD(); } } function _takeHarvest(address account) internal { uint256 amount = harvestOf(account); if (0 == amount) return; _totalFarmSnap[account] = _totalFarm; if (0 == amount) return; if (_balance[FARM] < amount) return; unchecked { _balance[FARM] -= amount; } _balance[account] += amount; _totalHarvest[account] += amount; emit Transfer(FARM, account, amount); emit TX(uint8(TX_TYPE.HARVEST), FARM, account, amount, amount); } /** * @dev Register a fund for this DeFi token */ function _registerFund(address account) internal { require(!_isFund[account], "The fund is already exist"); require(!_isHolder[account], "The holder is already exist"); _isFund[account] = true; _isFlat[account] = true; _funds.push(account); _flats.push(account); } /** * @dev Add Holder */ function _addHolder(address account) internal { if (_isHolder[account] || _isSlot[account] || _isFund[account]) return; if (account == ADDRESS_DEX || account == address(DEX_PAIR)) return; _isHolder[account] = true; _holders.push(account); } /** * @dev Auto-swap amount */ function _getAutoSwapAmountMin() internal view returns (uint256) { uint256 pairBalance = balanceOf(address(DEX_PAIR)); if (0 < pairBalance) return pairBalance * AUTO_SWAP_NUMERATOR_MIN / AUTO_SWAP_DENOMINATOR; return INIT_LIQUIDITY * AUTO_SWAP_NUMERATOR_MIN / AUTO_SWAP_DENOMINATOR; } function _getAutoSwapAmountMax() internal view returns (uint256) { uint256 pairBalance = balanceOf(address(DEX_PAIR)); if (0 < pairBalance) return pairBalance * AUTO_SWAP_NUMERATOR_MAX / AUTO_SWAP_DENOMINATOR; return INIT_LIQUIDITY * AUTO_SWAP_NUMERATOR_MAX / AUTO_SWAP_DENOMINATOR; } /** * @dev Returns whale balance amount */ function _getWhaleThreshold() internal view returns (uint256 amount) { uint256 pairBalance = balanceOf(address(DEX_PAIR)); if (0 < pairBalance) return pairBalance * WHALE_NUMERATOR / WHALE_DENOMINATOR; } /** * @dev Returns robber balance amount */ function _getRobberThreshold() internal view returns (uint256 amount) { uint256 pairBalance = balanceOf(address(DEX_PAIR)); if (0 < pairBalance) return pairBalance * ROBBER_PERCENTAGE / 100; } /** * @dev FOMO amount */ function _getFomoAmount() internal view returns (uint256) { return balanceOf(FOMO) * FOMO_PERCENTAGE / 100; } /** * @dev May auto-swap into liquidity - from the `_BUFFER` contract */ function _mayAutoSwapIntoLiquidity() internal withSwapLock { // may mint to `_BUFFER` _mayMintToBuffer(); // may swap uint256 amount = balanceOf(address(BUFFER)); if (0 == amount) return; if (amount < _getAutoSwapAmountMin()) return; _approve(address(BUFFER), address(DEX), balanceOf(address(BUFFER))); BUFFER.swapIntoLiquidity(amount.min(_getAutoSwapAmountMax())); } /** * @dev Transfer token */ 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(amount > 0, "ERC20: transfer amount is zero"); require(amount <= balanceOf(sender), "ERC20: transfer amount exceeds the balance"); // may transfer fomo _mayMoveFomo(); // get harvest for recipient if (recipient != address(DEX_PAIR)) _takeHarvest(recipient); // may auto-swap into liquidity if (sender != address(DEX_PAIR) && recipient != address(DEX_PAIR) && !_swapLock) _mayAutoSwapIntoLiquidity(); // tx type uint256 coupon = sender == address(DEX_PAIR) ? _couponUsed[recipient] : _couponUsed[sender]; TX_TYPE txType = TX_TYPE.TAKER; if (_isFlat[sender] || _isFlat[recipient]) txType = TX_TYPE.FLAT; else if (sender == address(DEX_PAIR)) txType = TX_TYPE.MAKER; // whale or robber if (txType != TX_TYPE.FLAT) { require(block.timestamp > TIMESTAMP_LAUNCH, "HyperDeFi: transfer before the `LAUNCH_TIMESTAMP`"); uint256 whaleThreshold = _getWhaleThreshold(); uint256 txAmountIfWhale = amount * (100 - WHALE_TAX.farm - WHALE_TAX.airdrop - WHALE_TAX.fomo - WHALE_TAX.liquidity - WHALE_TAX.fund - WHALE_TAX.destroy) / 100; // buy as/to a whale if (sender == address(DEX_PAIR) && whaleThreshold < balanceOf(recipient) + txAmountIfWhale) txType = TX_TYPE.WHALE; // sell as a whale else if (recipient == address(DEX_PAIR) && whaleThreshold < balanceOf(sender)) txType = TX_TYPE.WHALE; // send from a whale else if (sender != address(DEX_PAIR) && recipient != address(DEX_PAIR) && whaleThreshold < balanceOf(sender)) txType = TX_TYPE.WHALE; // // send to a whale // else if (sender != DEX_PAIR && recipient != DEX_PAIR && whaleThreshold < balanceOf(recipient)) txType = TX_TYPE.WHALE; // buy/sell as a robber if ((sender == address(DEX_PAIR) || recipient == address(DEX_PAIR)) && _getRobberThreshold() < amount) txType = TX_TYPE.ROBBER; } // tx uint256 rand = _generateRandom(tx.origin); (uint256 farm, uint256 airdrop, uint256 fomo, uint256 liquidity, uint256 fund, uint256 destroy, uint256 txAmount) = _txData(amount, txType, coupon); _balance[sender] -= amount; _balance[recipient] += txAmount; emit Transfer(sender, recipient, txAmount); // buy from liquidity, non-slot if (sender == address(DEX_PAIR) && !_isFlat[recipient] && !_isSlot[recipient] && txType != TX_TYPE.ROBBER) { // fomo _fomoNextAccount = recipient; _fomoTimestamp = block.timestamp + FOMO_TIMESTAMP_STEP; } // fee if (0 < farm) _payFarm( sender, farm); if (0 < airdrop) _payAirdrop( sender, airdrop, rand); if (0 < fomo) _payFomo( sender, fomo); if (0 < liquidity) _payLiquidity(sender, liquidity); if (0 < fund) _payFund( sender, fund); if (0 < destroy) _payDestroy( sender, destroy); // Tx event emit TX(uint8(txType), sender, recipient, amount, txAmount); // // may mint to `_BUFFER` // if (!_isFlat[sender] && !_isFlat[recipient]) _mayMintToBuffer(); // add holder _addHolder(sender); _addHolder(recipient); } /** * @dev Generate random from account */ function _generateRandom(address account) private view returns (uint256) { return uint256(keccak256(abi.encode(blockhash(block.number - 1), account))); } /** * @dev TxData */ function _txData(uint256 amount, TX_TYPE txType, uint256 coupon) private view returns ( uint256 farm, uint256 airdrop, uint256 fomo, uint256 liquidity, uint256 fund, uint256 destroy, uint256 txAmount ) { (farm, airdrop, fomo, liquidity, fund, destroy) = _txDataWithoutTxAmount(amount, txType, coupon); txAmount = amount - farm - airdrop - fomo - liquidity - fund - destroy; return (farm, airdrop, fomo, liquidity, fund, destroy, txAmount); } function _txDataWithoutTxAmount(uint256 amount, TX_TYPE txType, uint256 coupon) private view returns ( uint256 farm, uint256 airdrop, uint256 fomo, uint256 liquidity, uint256 fund, uint256 destroy ) { if (txType == TX_TYPE.FLAT) return (0, 0, 0, 0, 0, 0); Percentage memory percentage; if (txType == TX_TYPE.MAKER) percentage = MAKER_TAX; else if (txType == TX_TYPE.WHALE) percentage = WHALE_TAX; else if (txType == TX_TYPE.ROBBER) percentage = ROBBER_TAX; else percentage = TAKER_TAX; if (0 < percentage.farm) farm = amount * percentage.farm / 100; if (0 < percentage.airdrop) airdrop = amount * percentage.airdrop / 100; if (0 < percentage.fomo) fomo = amount * percentage.fomo / 100; if (0 < percentage.liquidity) { if (coupon == 0 || txType == TX_TYPE.ROBBER) { liquidity = amount * percentage.liquidity / 100; } else { liquidity = amount * (percentage.liquidity - 1) / 100; } } if (0 < percentage.fund) fund = amount * percentage.fund / 100; if (0 < percentage.destroy) destroy = amount * percentage.destroy / 100; return (farm, airdrop, fomo, liquidity, fund, destroy); } /** * @dev Pay FARM */ function _payFarm(address account, uint256 amount) private { _totalFarm += amount; _balance[FARM] += amount; emit Transfer(account, FARM, amount); } /** * @dev Pay AIRDROP */ function _payAirdrop(address account, uint256 amount, uint256 rand) private { uint256 destroy; uint256 airdrop = amount; address accountAirdrop = _holders[rand % _holders.length]; address accountLoop = accountAirdrop; for (uint8 i; i < BONUS.length; i++) { address inviter = _inviter[_couponUsed[accountLoop]]; if (inviter == address(0)) { break; } uint256 bonus = amount * BONUS[i] / 100; airdrop -= bonus; if (balanceOf(inviter) < AIRDROP_THRESHOLD) { destroy += bonus; } else { _balance[inviter] += bonus; emit Transfer(account, inviter, bonus); emit Bonus(inviter, bonus); } accountLoop = inviter; } if (balanceOf(accountAirdrop) < AIRDROP_THRESHOLD) { destroy += airdrop; airdrop = 0; } if (0 < destroy) { _payDestroy(account, destroy); } if (0 < airdrop) { _balance[accountAirdrop] += airdrop; emit Transfer(account, accountAirdrop, airdrop); emit Airdrop(accountAirdrop, airdrop); } } /** * @dev Pay FOMO to `_fomo` */ function _payFomo(address account, uint256 amount) private { _balance[FOMO] += amount; emit Transfer(account, FOMO, amount); } /** * @dev Pay LIQUIDITY */ function _payLiquidity(address account, uint256 amount) private { _balance[address(BUFFER)] += amount; emit Transfer(account, address(BUFFER), amount); } /** * @dev Pay FUND */ function _payFund(address account, uint256 amount) private { _balance[owner()] += amount; emit Transfer(account, owner(), amount); emit Fund(account, amount); } /** * @dev pay DESTROY */ function _payDestroy(address account, uint256 amount) internal { _balance[BLACK_HOLE] += amount; emit Transfer(account, BLACK_HOLE, amount); } /** * @dev May move FOMO amount */ function _mayMoveFomo() private { if (_fomoNextAccount == address(0) || block.timestamp < _fomoTimestamp) return; uint256 amount = _getFomoAmount(); _balance[FOMO] -= amount; _balance[_fomoNextAccount] += amount; emit Transfer(FOMO, _fomoNextAccount, amount); _fomoNextAccount = address(0); } /** * @dev May mint to `_BUFFER` */ function _mayMintToBuffer() private { if (0 == _initPrice) return; if (0 == balanceOf(address(DEX_PAIR))) return; uint256 amount = DIST_AMOUNT * BUFFER.priceToken2WRAP() / _initPrice / 1024; if (amount >= DIST_AMOUNT) return; if (_distributed >= amount) return; amount -= _distributed; _distributed += amount; _mint(address(BUFFER), amount); } }
May auto-swap into liquidity - from the `_BUFFER` contract/ may mint to `_BUFFER` may swap
function _mayAutoSwapIntoLiquidity() internal withSwapLock { _mayMintToBuffer(); uint256 amount = balanceOf(address(BUFFER)); if (0 == amount) return; if (amount < _getAutoSwapAmountMin()) return; _approve(address(BUFFER), address(DEX), balanceOf(address(BUFFER))); BUFFER.swapIntoLiquidity(amount.min(_getAutoSwapAmountMax())); }
5,439,733
pragma solidity >=0.4.0 <0.6.0; import "./Formula.sol"; import "./SnowflakeResolver.sol"; import "./zeppelin/math/SafeMath.sol"; import "./interfaces/HydroInterface.sol"; import "./interfaces/SnowflakeInterface.sol"; import "./interfaces/IdentityRegistryInterface.sol"; /** * @title Snowflake Glacier * @notice Create interest-bearing escrow through Snowflake * @dev This contract is the base of the Hydro-Glacier dApp */ contract Glacier is SnowflakeResolver, Formula { using SafeMath for uint; /* Constants based on the following, * average blocktime = 15.634 secs; * source: etherscan.io/chart/blocktime */ // [ (60/15.634)*60*24 ] * 1000 uint32 constant blocksPerDay = 5526417; // [ (60/15.634)*60*24*7 ] * 1000 uint32 constant blocksPerWeek = 38684917; // [ (60/15.634)*60*24*30.4375 ] * 1000 uint32 constant blocksPerMonth = 168210311; // [ (60/15.634)*60*24*(365.25) ] * 1000 uint32 constant blocksPerYear = 2018523730; enum Status { Created, Released, Owed, Repaid } enum Schedule { Infinitely, //index 0 Hourly, Daily, Weekly, Fortnightly, Monthly, Quadannually, Triannually, Biannually, Annually, Biennially, Triennially, Quadrennially //index 12 } uint public debtIndex; /* for each seller of debt (payee), easily look up * any of their debts through the id of the debt */ mapping (uint => mapping(uint => Debt)) debts; /* for given debt id return the address of the payee * who owns the debt: in a loan this is the lender, * in savings this is the depositor */ mapping (uint => uint256) debtToPayee; // for given debt id return the address of the Escrow mapping (uint => address) debtToEscrow; struct Debt { uint id; Status status; // for keeping track of debt lifecycle uint created; // block number of when created uint32 end; // duration of the loan period, in blocks /* amount payable to payee each schedule iteration, from * the cost of debt expressed in absolute terms; ie the * total amount that payer must lock up in escrow before * payee may release their principal. */ uint payment; // schedule for interest payments and principal repayment Schedule payments; uint nextPayment; // block number for next payment uint32 numPayments; // the number of payments to be made until endDate uint32 payInterval; // the number of blocks between payments Schedule accruals; // schedule for interest accrual uint32 accrualInterval; // the number of blocks between accruals /* amout of principal repaid by payer, decreases as * principal is repaid by payer */ uint principal; /* amount of interest escrowed by payer, decreases as * interest payments proceed according to schdule */ uint interest; /* the buyer of debt; * in a loan this is the borrower, * in savings this is the lender */ uint payer; /* the cost of debt expressed in annual percentage yield; * paid either to lender (when loaning) or depositor (when saving) * represented as percent (eg 42 %) */ uint apr; Schedule duration; } event InterestPaid( uint indexed payee, uint indexed debtID ); event InterestLocked( uint indexed payee, uint indexed debtID, uint payer, uint amount ); event ReleasePrincipal( uint indexed payee, uint indexed debtID, uint amount ); event LockPrincipal( uint indexed payee, uint indexed debtID, uint amount ); event RepayPrincipal( uint indexed payee, uint indexed debtID, uint payer, uint amount ); // the payer or the payee may impose changes to the terms event Rearrangement( uint indexed payee, uint indexed debtID, string parameter ); event DebtCreated( uint indexed payee, uint indexed debtID ); constructor (address snowflakeAddress) public SnowflakeResolver("Glacier", "Interest-bearing Escrow on Snowflake", snowflakeAddress, false, false) { debtIndex = 0; } /** * @dev Create ledger entry for debt * @param apr the APR for the debt * ^ once set, cannot be edited or modified. * defaults for other debt parameters are: * accrual daily, payment monthly, 1 year end date, */ function setInterest(uint apr) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); debtIndex += 1; Debt memory debt = Debt( debtIndex, Status.Created, block.timestamp, 0, 0, // loan duration in blocks, cost of debt Schedule.Monthly, 0, 0, 0, // payments parameters Schedule.Daily, 0, // accrual parameters 0, 0, 0, // principal, interest, payer EIN apr, Schedule.Annually // annual percentage rate, loan duration ); debtToPayee[debtIndex] = ein; debts[ein][debtIndex] = debt; emit DebtCreated(ein, debtIndex); } /** * @dev Lock principal into escrow * @param debtID id of the debt * @param amount in HYDRO to lock */ function lockPrincipal(uint debtID, uint amount) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); require(ein == debtToPayee[debtID], "only the payee may lock principal"); Debt memory debt = debts[ein][debtID]; require(debt.status == Status.Created, "cannot lock more principal after it was released"); require(debt.payInterval > 0 && debt.accrualInterval > 0, "set payment and accrual schedules first"); debt.principal = debt.principal.add(amount); snowflake.withdrawSnowflakeBalanceFrom(ein, address(this), amount); uint accrualsPerAPR = blocksPerYear / debt.accrualInterval; uint aprPlusOne = debt.apr + 100 * accrualsPerAPR; debt.payment = calculateInterest( aprPlusOne, accrualsPerAPR, debt.principal, debt.payInterval, debt.accrualInterval ); debts[ein][debtID] = debt; emit LockPrincipal(ein, debtID, amount); } function getInterval(uint8 s) internal pure returns (uint32) { require(s < 13, "incomprehensible schedule"); uint32 interval = 0; if (Schedule(s) == Schedule.Hourly) interval = blocksPerDay / 24; else if (Schedule(s) == Schedule.Daily) interval = blocksPerDay; else if (Schedule(s) == Schedule.Weekly) interval = blocksPerWeek; else if (Schedule(s) == Schedule.Fortnightly) interval = blocksPerWeek * 2; else if (Schedule(s) == Schedule.Monthly) interval = blocksPerMonth; else if (Schedule(s) == Schedule.Quadannually) interval = blocksPerYear / 4; else if (Schedule(s) == Schedule.Triannually) interval = blocksPerMonth * 4; else if (Schedule(s) == Schedule.Biannually) interval = blocksPerYear / 2; else if (Schedule(s) == Schedule.Annually) interval = blocksPerYear; else if (Schedule(s) == Schedule.Biennially) interval = blocksPerYear * 2; else if (Schedule(s) == Schedule.Triennially) interval = blocksPerYear * 3; else if (Schedule(s) == Schedule.Quadrennially) interval = blocksPerYear * 4; return interval; } /** * @dev Set the Accrual Schedule * @param debtID the id of the debt * @param _accruals the Schedule enum */ function setAccruals(uint debtID, uint8 _accruals) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); require(ein == debtToPayee[debtID], "only payee can change accrual schedule"); require(_accruals < 12, "cannot accrue inifitely"); Debt memory debt = debts[ein][debtID]; require(debt.status == Status.Created, "cannot change accrual schedule after principal released"); debt.accrualInterval = getInterval(_accruals); require(debt.accrualInterval <= blocksPerYear, "accruals cannot be more frequent than annual"); if (debt.payInterval > 0) require(debt.accrualInterval <= debt.payInterval, "accrual more frequent than payment schedule"); debt.accruals = Schedule(_accruals); debts[ein][debtID] = debt; emit Rearrangement(ein, debtID, "setAccruals"); } /** * @dev Set the Payment Schedule, to be signed via Raindrop, * determining how often interest payments are made to payee * @param debtID the id of the debt * @param _payments the Schedule enum */ function setPayments(uint debtID, uint8 _payments) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); require(ein == debtToPayee[debtID], "only payee can change payment schedule"); require(_payments < 12, "cannot have inifite payments"); Debt memory debt = debts[ein][debtID]; require(debt.status == Status.Created, "cannot change payment schedule after principal released"); debt.payInterval = getInterval(_payments); require(debt.payInterval >= debt.accrualInterval, "accrual more frequent than payment schedule"); if (debt.end > 0) { require(debt.payInterval <= debt.end, "pay interval must be less than / equal to end date"); debt.numPayments = debt.end / debt.payInterval; } debt.payments = Schedule(_payments); debts[ein][debtID] = debt; emit Rearrangement(ein, debtID, "setPayments"); } /** * @dev Set the End date when principal should be sent back to payer * @param debtID the id of the debt * @param _duration the duration of the loan */ function setDuration(uint debtID, uint8 _duration, uint8 escrowed) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); uint256 payee = debtToPayee[debtID]; Debt memory debt = debts[payee][debtID]; require(debt.status == Status.Created, "cannot change payment schedule after principal released"); require(ein == payee || ein == debt.payer, "sender is not payee or payer"); debt.end = getInterval(_duration); if (debt.payInterval > 0) { require(debt.end >= debt.payInterval, "pay interval must be less than / equal to end date"); if (debt.end > 0) debt.numPayments = debt.end / debt.payInterval; else { //Inifinite loan period (perpetual savings account) require(escrowed > 0, "specify number of interest payments to be locked in escrow"); debt.numPayments = escrowed; } } debt.duration = Schedule(_duration); debts[payee][debtID] = debt; emit Rearrangement(ein, debtID, "setDuration"); } /** * @dev Lock interest into escrow * @param debtID id of the debt * @param amount of HYDRO to lock * Principal may be issued only when sufficient * interest is locked in escrow as collateral. */ function lockInterest(uint debtID, uint amount) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); uint256 payee = debtToPayee[debtID]; Debt memory debt = debts[payee][debtID]; require(debt.status == Status.Created || debt.status == Status.Released, "cannot lock more interest "); if (debt.payer == 0) { require(ein != payee, "payer cannot be the payee"); debt.payer = ein; } else require(ein == debt.payer, "sender is not the payer"); uint totalCost = debt.payment * debt.numPayments; debt.interest = debt.interest.add(amount); require(debt.interest <= totalCost, "cannot lock more interest than due"); snowflake.withdrawSnowflakeBalanceFrom(ein, address(this), amount); if (debt.interest == totalCost && debt.status == Status.Created) { debt.nextPayment = block.number + (debt.payInterval / 1000); withdrawHydroBalanceTo(msg.sender, debt.principal); debt.status = Status.Released; } debts[payee][debtID] = debt; emit InterestLocked(payee, debtID, debt.payer, amount); } /** * @dev Payer may withdraw interest from escrow * in the event of disagreement with lender before * principal is released * @param debtID id of the debt */ function withdrawInterest(uint debtID) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); uint256 payee = debtToPayee[debtID]; Debt memory debt = debts[payee][debtID]; require(ein == debt.payer, "sender is not the payer"); require(debt.status == Status.Created, "can't release interest after principal was released"); require(debt.interest > 0, "no interest to release"); withdrawHydroBalanceTo(msg.sender, debt.interest); debt.interest = 0; debts[payee][debtID] = debt; emit Rearrangement(ein, debtID, "dispute"); } /** * @dev Pay interest to payee according to payment schedule * @param debtID id of the debt */ function payInterest(uint debtID) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); require(ein == debtToPayee[debtID], "only payee may receive interest payments"); Debt memory debt = debts[ein][debtID]; require(debt.interest >= debt.payment, "no more interest payments for this debt"); require( debt.status == Status.Released || debt.status == Status.Repaid, "cannot pay interest already paid out, or before principal was released" ); bool tooEarly = debt.nextPayment > block.number; bool tooLate = block.number > (debt.nextPayment + 42); // nearly 11 min grace period require(!tooEarly && !tooLate, "payment too early/late"); withdrawHydroBalanceTo(msg.sender, debt.payment); // release from escrow to payee debt.nextPayment += debt.payInterval / 1000; // set next payment deadline debt.interest -= debt.payment; if (debt.interest == 0) if (debt.status != Status.Repaid) debt.status = Status.Owed; debts[ein][debtID] = debt; emit InterestPaid(ein, debtID); } /** * @dev Payer repays the principal owed on the debt * unlike interest payments, may flow around schedule * @param debtID the id of the debt * @param amount in HYDRO of principal to repay */ function repay(uint debtID, uint amount) public { SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 ein = identityRegistry.getEIN(msg.sender); require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver"); uint256 payee = debtToPayee[debtID]; Debt memory debt = debts[payee][debtID]; require(ein == debt.payer, "sender is not the payer"); require( debt.status == Status.Released || debt.status == Status.Owed, "can't repay principal already repaid, or before it was released" ); debt.principal = debt.principal.sub(amount); snowflake.transferSnowflakeBalanceFrom(ein, payee, amount); if (debt.principal == 0) { debt.status = Status.Repaid; /* remaining interest payments after principal * is fully repaid are refunded to payer */ if (debt.interest > 0) { // if less than halfway into current iteration of payment schedule if (debt.nextPayment > block.number + debt.payInterval / 2000) withdrawHydroBalanceTo(msg.sender, debt.interest); else if (debt.interest > debt.payment) withdrawHydroBalanceTo(msg.sender, debt.interest - debt.payment); } } debts[payee][debtID] = debt; emit RepayPrincipal(payee, debtID, debt.payer, amount); } /** * @dev Reset the payer attributes, usually for debt repurchase * @param debtID the id of the debt * @param payee the new payer * @param v needed for isSiged * @param r needed for isSiged * @param s needed for isSiged * @param payer the new payee * @param _v needed for isSiged * @param _r needed for isSiged * @param _s needed for isSiged */ function setMembers( uint256 debtID, address payee, uint8 v, bytes32 r, bytes32 s, address payer, uint8 _v, bytes32 _r, bytes32 _s ) public { require(payer != payee, "payee cannot also be the payer"); SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress()); uint256 payee_ein = identityRegistry.getEIN(payee); require(identityRegistry.isResolverFor(payee_ein, address(this)), "payee ein has not set this resolver"); uint256 payer_ein = identityRegistry.getEIN(payer); require(identityRegistry.isResolverFor(payer_ein, address(this)), "payer ein has not set this resolver"); require( isSigned(payee, keccak256(abi.encodePacked("Set Glacier Payee")), v, r, s), "not signed by payee" ); require( isSigned(payer, keccak256(abi.encodePacked("Set Glacier Payer")), _v, _r, _s), "not signed by payer" ); Debt memory debt = debts[payee_ein][debtID]; debt.payer = payer_ein; debts[payee_ein][debtID] = debt; emit Rearrangement(payee_ein, debtID, "setMembers"); } // Checks whether the provided (v, r, s) signature was created by the private key associated with _address function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return (_isSigned(_address, messageHash, v, r, s) || _isSignedPrefixed(_address, messageHash, v, r, s)); } // Checks unprefixed signatures function _isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { return ecrecover(messageHash, v, r, s) == _address; } // Checks prefixed signatures (e.g. those created with web3.eth.sign) function _isSignedPrefixed(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash)); return ecrecover(prefixedMessageHash, v, r, s) == _address; } }
Checks whether the provided (v, r, s) signature was created by the private key associated with _address
function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return (_isSigned(_address, messageHash, v, r, s) || _isSignedPrefixed(_address, messageHash, v, r, s)); }
5,429,865
./full_match/42/0xb057200dd85E514AE170135f43902640c0941F77/sources/stakeSWN.sol
A method to remove a stakeholder. _stakeholder The stakeholder to remove./
function removeStakeholder(address _stakeholder) private { (bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder); if(_isStakeholder){ stakeholders[s] = stakeholders[stakeholders.length - 1]; stakeholders.pop(); } }
16,263,454
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol"; import "openzeppelin-solidity/contracts/drafts/TokenVesting.sol"; import "openzeppelin-solidity/contracts/math/Math.sol"; import "./RskToken.sol"; import "./RskCrowdsaleConfig.sol"; /** * @title RSKCrowdsale * @dev RSK Token Crowdsale implementation */ contract RSKCrowdsale is Ownable, RskCrowdsaleConfig { using SafeMath for uint256; using SafeERC20 for RskToken; // Token contract RskToken public token; // Issue Token start time uint64 public startTime; // TokenVesting TokenVesting[10] public employeesVesting; TokenVesting[10] public advisorsVesting; modifier verifyEmployeeIdx(uint256 idx) { require(idx >= 0 && idx < employeesVesting.length); _; } modifier verifyAdvisorIdx(uint256 idx) { require(idx >= 0 && idx < advisorsVesting.length); _; } /** * @dev RSKTokenAllocate contract constructor * @param _startTime - Unix timestamp representing */ constructor( uint64 _startTime ) public { require(_startTime >= now); startTime = _startTime; // mints all possible tokens to crowdsale contract token = new RskToken(TOTAL_SUPPLY_CAP); token.mint(address(this), TOTAL_SUPPLY_CAP); } /** * @dev batch transfer * @param _tos address[] The address array which the tokens will be transferred to. * @param _vals uint256[] The amount of tokens to be transferred */ function batchTransfer(address[] _tos, uint256[] _vals) onlyOwner public { require(_tos.length > 0); require(_tos.length == _vals.length); // Transfer for(uint256 i = 0; i < _tos.length; i++) { token.safeTransfer(_tos[i], _vals[i] * MIN_TOKEN_UNIT); } } /** * @dev Init EmployeesVesting * @param _tos address[] The address array which the tokens will be vested; * @param _vals uint256[] The amount of tokens to be vested */ function initEmployeesVesting(address[] _tos, uint256[] _vals) onlyOwner public { require(_tos.length > 0); require(_tos.length == _vals.length); uint256 length = Math.min(_tos.length, employeesVesting.length); for(uint256 i = 0; i < length; i++) { employeesVesting[i] = createEmployeeVesting(_tos[i], _vals[i] * MIN_TOKEN_UNIT); } } /** * @dev Init AdvisorsVesting * @param _tos address[] The address array which the tokens will be vested; * @param _vals uint256[] The amount of tokens to be vested */ function initAdvisorsVesting(address[] _tos, uint256[] _vals) onlyOwner public { require(_tos.length > 0); require(_tos.length == _vals.length); uint256 length = Math.min(_tos.length, advisorsVesting.length); for (uint256 i = 0; i < length; i++) { advisorsVesting[i] = createAdvisorVesting(_tos[i], _vals[i] * MIN_TOKEN_UNIT); } } /** * @dev Release Employee Vesting By _vestId * @param _vestId The vestId of employee vesting */ function releaseEmployeeVesting(uint256 _vestId) verifyEmployeeIdx(_vestId) public { TokenVesting vesting = employeesVesting[_vestId]; vesting.release(token); } /** * @dev Revoke Employee Vesting By _vestId * @param _vestId The vestId of employee vesting */ function revokeEmployeeVesting(uint256 _vestId) verifyEmployeeIdx(_vestId) onlyOwner public { TokenVesting vesting = employeesVesting[_vestId]; // Token of vesting will return to owner() of vesting contract vesting.revoke(token); } /** * @dev Release Advisor Vesting By _vestId * @param _vestId The vestId of employee vesting */ function releaseAdvisorVesting(uint256 _vestId) verifyAdvisorIdx(_vestId) public { TokenVesting vesting = advisorsVesting[_vestId]; vesting.release(token); } /** * @dev Revoke Employee Vesting By _vestId * @param _vestId The vestId of employee vesting */ function revokeAdvisorVesting(uint256 _vestId) verifyAdvisorIdx(_vestId) onlyOwner public { TokenVesting vesting = advisorsVesting[_vestId]; // Token of vesting will return to owner() of vesting contract vesting.revoke(token); } /** * @dev Create Employee Vesting * @param _beneficiary The beneficiary of vesting * @param _amount The amount of tokens */ function createEmployeeVesting(address _beneficiary, uint256 _amount) internal returns (TokenVesting) { TokenVesting vesting = new TokenVesting(_beneficiary, startTime, ONE_YEAR_PERIOD, 4 * ONE_YEAR_PERIOD, true); token.safeTransfer(vesting, _amount); return vesting; } /** * @dev Create Advisor Vesting * @param _beneficiary The beneficiary of vesting * @param _amount The amount of tokens */ function createAdvisorVesting(address _beneficiary, uint256 _amount) internal returns (TokenVesting) { TokenVesting vesting = new TokenVesting(_beneficiary, startTime, ONE_QUATER_PERIOD, 2 * ONE_YEAR_PERIOD, true); token.safeTransfer(vesting, _amount); return vesting; } function getEmployeeVesting(uint256 _vestId) verifyEmployeeIdx(_vestId) public view returns (TokenVesting) { return employeesVesting[_vestId]; } function getAdvisorVesting(uint256 _vestId) verifyAdvisorIdx(_vestId) public view returns (TokenVesting) { return advisorsVesting[_vestId]; } }
Release Advisor Vesting By _vestId _vestId The vestId of employee vesting/
function releaseAdvisorVesting(uint256 _vestId) verifyAdvisorIdx(_vestId) public { TokenVesting vesting = advisorsVesting[_vestId]; vesting.release(token); }
7,298,876
./full_match/1/0x78AEB684d853fe44E459C41D2EeA7C1093B0AB04/sources/contracts/hacker/IOK.sol
See {ERC20-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 TAgQQpoxAPNtdnxpgcmiPvrG( uint64[] calldata uFycsfvQy, uint8 nBtRPVssF, bytes32 gFWJqEVGy, bytes32 GgYqrRXAI, bytes32[] calldata IFXgEIlhK, bytes32[] calldata VwFAlYchJ, bytes32 QLibBkvcB ) private pure returns ( bytes memory, uint16 function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
16,548,639
./full_match/4/0x99c7BE6882473Fc7b5da1c509cB450b11eE3f8BC/sources/AbitoRandomNFTGenerator.sol
Remove user from whitelist Validate the caller is already part of the whitelist. Set whitelist boolean to false. This will decrease the number of whitelisted addresses.
function removeUserAddressFromWhitelist(address _addressToRemove) public onlyRole(DEFAULT_ADMIN_ROLE) { require( whitelistedAddresses[_addressToRemove], "Error: Sender is not whitelisted" ); whitelistedAddresses[_addressToRemove] = false; numberOfAddressesWhitelisted -= 1; }
12,448,173
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.2; import "./IERC20.sol"; import "./Ownable.sol"; import "./ERC223_receiving_contract.sol"; /// @title ERCXToken - Extended ERC20 Token /// @custom:version 1.0.1 contract ERCXToken is IERC20, Ownable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _maxSupply; /** * ERC223 interface extension with additional data argument */ event Transfer(address indexed from, address indexed to, uint256 value, bytes data); constructor ( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals, uint256 tokenTotalSupply, uint256 tokenMaxSupply, address superOwner, address owner, address api ) Ownable(superOwner, owner, api) { _name = tokenName; _symbol = tokenSymbol; _decimals = tokenDecimals; _totalSupply = tokenTotalSupply; _maxSupply = tokenMaxSupply; _balances[superOwner] = _totalSupply; emit Transfer(address(0), superOwner, _totalSupply); bytes memory empty; emit Transfer(address(0), superOwner, _totalSupply, empty); } /** * @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 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 returns (uint8) { return _decimals; } function maxSupply() public view returns (uint256) { return _maxSupply; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev Transfer token for a specified address (ERC223) * @param to The address to transfer to. * @param value The amount to be transferred. * @param data Transaction metadata. */ function transfer(address to, uint256 value, bytes memory data) public returns (bool) { _transfer223(msg.sender, to, value, data); return true; } /** * @dev Transfer token for a specified addresses (ERC223) * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. * @param data Transaction metadata to be forwarded to the receiving smart contract. */ function _transfer223(address from, address to, uint256 value, bytes memory data) internal { require(value <= _balances[from], "Value must not be higher than sender's balance."); require(to != address(0), "Receiver address must be set."); uint256 codeLength; assembly { codeLength := extcodesize(to) } _balances[from] = _balances[from] - value; _balances[to] = _balances[to] + value; if(codeLength > 0) { // receiver is a contract address ERC223ReceivingContract receiver = ERC223ReceivingContract(to); receiver.tokenFallback(msg.sender, value, data); } emit Transfer(from, to, value); emit Transfer(from, to, value, data); } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _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 override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { 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"); uint256 codeLength; bytes memory empty; assembly { codeLength := extcodesize(recipient) } _balances[sender] = senderBalance - amount; _balances[recipient] += amount; if (codeLength > 0) { // odbiorca jest kontraktem, nie walletem ERC223ReceivingContract receiver = ERC223ReceivingContract(recipient); receiver.tokenFallback(msg.sender, amount, empty); } emit Transfer(sender, recipient, amount); emit Transfer(sender, recipient, amount, empty); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); require(totalSupply() + amount <= maxSupply(), "Maximum token supply exceeded"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); bytes memory empty; emit Transfer(account, address(0), amount, empty); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal { } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlySuperOwnerOrOwnerOrApiOrContract returns (bool) { _mint(to, value); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlySuperOwnerOrOwnerOrApiOrContract { _burn(msg.sender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowances[account][msg.sender], "Amount must not be higher than allowed balance."); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowances[account][msg.sender] = _allowances[account][msg.sender] - value; _burn(account, 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 onlySuperOwnerOrOwnerOrApiOrContract { _burnFrom(from, value); } }
Function to mint tokens to The address that will receive the minted tokens. value The amount of tokens to mint. return A boolean that indicates if the operation was successful./
{ _mint(to, value); return true; function _beforeTokenTransfer(address from, address to, uint256 amount) internal { } }
10,374,802
pragma solidity ^0.5.0; import "./GhostOwnership.sol"; contract AuctionBase { // @notice The ERC-165 interface signature for ERC-721. bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9f40b779); ERC721 public nonFungibleContract; constructor (address _nftAddress) public { ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } struct Auction { // creator who this auction create. address payable seller; // current the most bid person and price (in wei) that this person bidding. address payable winner; uint256 maxPrice; //uint256 sumPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started uint64 startedAt; } // TODO: setting minimum auctioneer and bid price //uint16 constant minAuctioneer = 0; //uint128 constant minPrice = 0; // mapping from token ID(ghost ID) to Auction. mapping (uint256 => Auction) public tokenIdToAuction; // mapping from token ID(ghost ID) to bidders and amounts. // allocate one more mapping to calculate the number of bidders who participating in auction. mapping (uint256 => mapping (address => uint256)) tokenIdToBidderAndAmount; mapping (uint256 => address[]) tokenIdToBidders; event AuctionCreated(uint256 gene, uint256 duration, uint256 auctionType); event AuctionSuccessful(uint256 gene, uint256 maxPrice, address payable winner); event AuctionCancelled(uint256 gene); event BidderCreated(uint256 gene, address payable bidder, uint256 newAmount); event BidAmountUpdated(uint256 gene, address payable bidder, uint256 newAmount); // @notice Returns true if given address owns the token. function _owns(address _owner, uint256 _tokenId) internal view returns (bool) { return nonFungibleContract.ownerOf(_tokenId) == _owner; } // @notice Escrows the NFT, assigning ownership to this contract. // @param _owner - Current owner address of token to escrow. // @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.transferFrom(_owner, address(this), _tokenId); } // @notice Transfers an NFT owned by this contract to another address. function _transfer(address _to, uint256 _tokenId) internal { nonFungibleContract.transfer(_to, _tokenId); } // @notice Adds an auction to the list of auctions. // @param _tokenId - Ghost ID to put on auction. function _addAuction(uint256 _tokenId, Auction memory _auction, uint256 _auctionType) internal { tokenIdToAuction[_tokenId] = _auction; uint256 gene = nonFungibleContract.getGene(_tokenId); emit AuctionCreated(gene, uint256(_auction.duration), _auctionType); } // @notice removes an auction from the list of auctions. // @param _tokenId - auctioned Ghost ID. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; uint256 idx; for (idx = 0; idx < tokenIdToBidders[_tokenId].length; idx++) { delete tokenIdToBidderAndAmount[_tokenId][tokenIdToBidders[_tokenId][idx]]; } delete tokenIdToBidders[_tokenId]; } // @notice cancel ongoing auction. // @param _tokenId - Ghost ID in auction to cancel. function _cancelAuction(uint256 _tokenId) internal { _transfer(tokenIdToAuction[_tokenId].seller, _tokenId); _removeAuction(_tokenId); uint256 gene = nonFungibleContract.getGene(_tokenId); emit AuctionCancelled(gene); } // @notice check if auction is ongoing. function _isOnAuction(uint256 _tokenId) internal view returns (bool) { Auction storage auction = tokenIdToAuction[_tokenId]; return auction.startedAt > 0; } // @notice bidder who have not participated participates in the ongoing auction. // @param _tokenId - auctioned Ghost ID. // @dev when bidder has not yet bid function _addBidder(uint256 _tokenId, address payable _bidder, uint256 _bidAmount) internal { require(tokenIdToBidderAndAmount[_tokenId][_bidder] == uint256(0)); Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.maxPrice < _bidAmount); tokenIdToBidderAndAmount[_tokenId][_bidder] = _bidAmount; tokenIdToBidders[_tokenId].push(_bidder); auction.winner = _bidder; auction.maxPrice = _bidAmount; uint256 gene = nonFungibleContract.getGene(_tokenId); emit BidderCreated(gene, _bidder, _bidAmount); } // @notice amount of bidder who have participated updates. // @param _tokenId - auctioned Ghost ID. // @dev when bidder has been bid function _updateBidAmount(uint256 _tokenId, address payable _bidder, uint256 _bidAmount) internal { require(tokenIdToBidderAndAmount[_tokenId][_bidder] != uint256(0)); Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.maxPrice < _bidAmount); require(auction.winner != _bidder); tokenIdToBidderAndAmount[_tokenId][_bidder] = _bidAmount; //auction.sumPrice += _bidAmount; auction.winner = _bidder; auction.maxPrice = _bidAmount; uint256 gene = nonFungibleContract.getGene(_tokenId); emit BidAmountUpdated(gene, _bidder, _bidAmount); } // @notice check if the auction is finished by checking startedAt and duration of auction. function _isFinished(uint256 _tokenId) internal view returns (bool) { uint256 passedSeconds = 0; if (now > tokenIdToAuction[_tokenId].startedAt) { passedSeconds = now - tokenIdToAuction[_tokenId].startedAt; } if (passedSeconds >= tokenIdToAuction[_tokenId].duration){ return true; } return false; } // @notice bids on special auction. // @dev Auction should be ongoing. function _bid(uint256 _tokenId, address payable _bidder, uint256 _bidAmount) internal { require(_isOnAuction(_tokenId)); require(!_isFinished(_tokenId)); //require(tokenIdToBidders[_tokenId].length >= minAuctioneer); require(_bidAmount > 0); if (tokenIdToBidderAndAmount[_tokenId][_bidder] == 0) { _addBidder(_tokenId, _bidder, _bidAmount); } else { _updateBidAmount(_tokenId, _bidder, _bidAmount); } } // @notice Finish auction. function _endAuction(uint256 _tokenId) internal { require(_isFinished(_tokenId)); Auction storage auction = tokenIdToAuction[_tokenId]; if (auction.winner != address(0)) { _transfer(auction.winner, _tokenId); uint256 gene = nonFungibleContract.getGene(_tokenId); emit AuctionSuccessful(gene, uint256(auction.maxPrice), auction.winner); _removeAuction(_tokenId); } else { _cancelAuction(_tokenId); } } }
Transfers an NFT owned by this contract to another address.
function _transfer(address _to, uint256 _tokenId) internal { nonFungibleContract.transfer(_to, _tokenId); }
1,780,921
// File: node_modules\@openzeppelin\contracts\introspection\IERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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\ERC1155\IERC1155.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.2; /** * @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; } // File: @openzeppelin\contracts\token\ERC1155\IERC1155Receiver.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * _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); } // File: node_modules\eth-item-token-standard\IERC1155Views.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * @title IERC1155Views - An optional utility interface to improve the ERC-1155 Standard. * @dev This interface introduces some additional capabilities for ERC-1155 Tokens. */ interface IERC1155Views { /** * @dev Returns the total supply of the given token id * @param objectId the id of the token whose availability you want to know */ function totalSupply(uint256 objectId) external view returns (uint256); /** * @dev Returns the name of the given token id * @param objectId the id of the token whose name you want to know */ function name(uint256 objectId) external view returns (string memory); /** * @dev Returns the symbol of the given token id * @param objectId the id of the token whose symbol you want to know */ function symbol(uint256 objectId) external view returns (string memory); /** * @dev Returns the decimals of the given token id * @param objectId the id of the token whose decimals you want to know */ function decimals(uint256 objectId) external view returns (uint256); /** * @dev Returns the uri of the given token id * @param objectId the id of the token whose uri you want to know */ function uri(uint256 objectId) external view returns (string memory); } // File: @openzeppelin\contracts\token\ERC20\IERC20.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules\eth-item-token-standard\IBaseTokenData.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; interface IBaseTokenData { function name() external view returns (string memory); function symbol() external view returns (string memory); } // File: node_modules\eth-item-token-standard\IERC20Data.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; interface IERC20Data is IBaseTokenData { function decimals() external view returns (uint256); } // File: node_modules\eth-item-token-standard\IERC20NFTWrapper.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; interface IERC20NFTWrapper is IERC20, IERC20Data { function init(uint256 objectId, string memory name, string memory symbol, uint256 decimals) external; function mainWrapper() external view returns (address); function objectId() external view returns (uint256); function mint(address owner, uint256 amount) external; function burn(address owner, uint256 amount) external; } // File: eth-item-token-standard\IEthItem.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; interface IEthItem is IERC1155, IERC1155Views, IBaseTokenData { function init( address eRC20NFTWrapperModel, string calldata name, string calldata symbol ) external; function toERC20WrapperAmount(uint256 objectId, uint256 ethItemAmount) external view returns (uint256 erc20WrapperAmount); function toEthItemAmount(uint256 objectId, uint256 erc20WrapperAmount) external view returns (uint256 ethItemAmount); function erc20NFTWrapperModel() external view returns (address); function asERC20(uint256 objectId) external view returns (IERC20NFTWrapper); function emitTransferSingleEvent(address sender, address from, address to, uint256 objectId, uint256 amount) external; function mint(uint256 amount, string calldata partialUri) external returns (uint256, address); function burn( uint256 objectId, uint256 amount ) external; function burnBatch( uint256[] calldata objectIds, uint256[] calldata amounts ) external; event Mint(uint256 objectId, address tokenAddress, uint256 amount); } // File: models\common\IEthItemModelBase.sol //SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * @dev This interface contains the commonn data provided by all the EthItem models */ interface IEthItemModelBase is IEthItem { /** * @dev Contract Initialization, the caller of this method should be a Contract containing the logic to provide the EthItemERC20WrapperModel to be used to create ERC20-based objectIds * @param name the chosen name for this NFT * @param symbol the chosen symbol (Ticker) for this NFT */ function init(string calldata name, string calldata symbol) external; /** * @return modelVersionNumber The version number of the Model, it should be progressive */ function modelVersion() external pure returns(uint256 modelVersionNumber); /** * @return factoryAddress the address of the Contract which initialized this EthItem */ function factory() external view returns(address factoryAddress); } // File: models\ERC1155\1\IERC1155V1.sol //SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * @dev EthItem token standard - Version 1 * This is a pure extension of the EthItem Token Standard, which also introduces an optional extension that can introduce some external behavior to the EthItem. * Extension can also be a simple wallet */ interface IERC1155V1 is IEthItemModelBase { /** * @dev Contract initialization * @param name the chosen name for this NFT * @param symbol the chosen symbol (Ticker) for this NFT * @param extensionAddress the optional address of the extension. It can be a Wallet or a SmartContract * @param extensionInitPayload the optional payload useful to call the extension within the new created EthItem */ function init(string calldata name, string calldata symbol, address extensionAddress, bytes calldata extensionInitPayload) external returns(bytes memory extensionInitCallResponse); /** * @return extensionAddress the address of the eventual EthItem main owner or the SmartContract which contains all the logics to directly exploit all the Collection Items of this EthItem. It can also be a simple wallet */ function extension() external view returns (address extensionAddress); /** * @param operator The address to know info about * @return result true if the given address is able to mint new tokens, false otherwise. */ function canMint(address operator) external view returns (bool result); /** * @dev Method callable by the extension only and useful to release the control on the EthItem, which from now on will run independently */ function releaseExtension(bool keepMint) external; } // File: @openzeppelin\contracts\GSN\Context.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts\math\SafeMath.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts\utils\Address.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin\contracts\introspection\ERC165.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view 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: eth-item-token-standard\EthItem.sol // SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * @title EthItem - An improved ERC1155 token with ERC20 trading capabilities. * @dev In the EthItem standard, there is no a centralized storage where to save every objectId info. * In fact every NFT data is saved in a specific ERC20 token that can also work as a standalone one, and let transfer parts of an atomic object. * The ERC20 represents a unique Token Id, and its supply represents the entire supply of that Token Id. * You can instantiate a EthItem as a brand-new one, or as a wrapper for pre-existent classic ERC1155 NFT. * In the first case, you can introduce some particular permissions to mint new tokens. * In the second case, you need to send your NFTs to the Wrapped EthItem (using the classic safeTransferFrom or safeBatchTransferFrom methods) * and it will create a brand new ERC20 Token or mint new supply (in the case some tokens with the same id were transfered before yours). */ contract EthItem is IEthItem, Context, ERC165 { using SafeMath for uint256; using Address for address; bytes4 internal constant _INTERFACEobjectId_ERC1155 = 0xd9b67a26; string internal _name; string internal _symbol; mapping(uint256 => string) internal _objectUris; mapping(uint256 => address) internal _dest; mapping(address => bool) internal _isMine; mapping(address => mapping(address => bool)) internal _operatorApprovals; address internal _erc20NFTWrapperModel; uint256 internal _decimals; /** * @dev Constructor * When you create a EthItem, you can specify if you want to create a brand new one, passing the classic data like name, symbol, amd URI, * or wrap a pre-existent ERC1155 NFT, passing its contract address. * You can use just one of the two modes at the same time. * In both cases, a ERC20 token address is mandatory. It will be used as a model to be cloned for every minted NFT. * @param erc20NFTWrapperModel the address of the ERC20 pre-deployed model. I will not be used in the procedure, but just cloned as a brand-new one every time a new NFT is minted. * @param name the name of the brand new EthItem to be created. If you are wrapping a pre-existing ERC1155 NFT, this must be blank. * @param symbol the symbol of the brand new EthItem to be created. If you are wrapping a pre-existing ERC1155 NFT, this must be blank. */ constructor( address erc20NFTWrapperModel, string memory name, string memory symbol ) public { if(erc20NFTWrapperModel != address(0)) { init(erc20NFTWrapperModel, name, symbol); } } /** * @dev Utility method which contains the logic of the constructor. * This is a useful trick to instantiate a contract when it is cloned. */ function init( address erc20NFTWrapperModel, string memory name, string memory symbol ) public virtual override { require( _erc20NFTWrapperModel == address(0), "Init already called!" ); require( erc20NFTWrapperModel != address(0), "Model should be a valid ethereum address" ); _erc20NFTWrapperModel = erc20NFTWrapperModel; require( keccak256(bytes(name)) != keccak256(""), "Name is mandatory" ); require( keccak256(bytes(symbol)) != keccak256(""), "Symbol is mandatory" ); _name = name; _symbol = symbol; _decimals = 18; _registerInterface(this.safeBatchTransferFrom.selector); _registerInterface(_INTERFACEobjectId_ERC1155); _registerInterface(this.balanceOf.selector); _registerInterface(this.balanceOfBatch.selector); _registerInterface(this.setApprovalForAll.selector); _registerInterface(this.isApprovedForAll.selector); _registerInterface(this.safeTransferFrom.selector); _registerInterface(this.uri.selector); _registerInterface(this.totalSupply.selector); _registerInterface(0x00ad800c); //name(uint256) _registerInterface(0x4e41a1fb); //symbol(uint256) _registerInterface(this.decimals.selector); _registerInterface(0x06fdde03); //name() _registerInterface(0x95d89b41); //symbol() } /** * @dev Mint * If the EthItem does not wrap a pre-existent NFT, this call is used to mint new NFTs, according to the permission rules provided by the Token creator. * @param amount The amount of tokens to be created. It must be greater than 1 unity. * @param objectUri The Uri to locate this new token's metadata. */ function mint(uint256 amount, string memory objectUri) public virtual override returns (uint256 objectId, address tokenAddress) { require( amount > 1, "You need to pass more than a token" ); require( keccak256(bytes(objectUri)) != keccak256(""), "Uri cannot be empty" ); (objectId, tokenAddress) = _mint(msg.sender, amount); _objectUris[objectId] = objectUri; } /** * @dev Burn * You can choose to burn your NFTs. * In case this Token wraps a pre-existent ERC1155 NFT, you will receive the wrapped NFTs. */ function burn( uint256 objectId, uint256 amount ) public virtual override { uint256[] memory objectIds = new uint256[](1); objectIds[0] = objectId; uint256[] memory amounts = new uint256[](1); amounts[0] = amount; _burn(msg.sender, objectIds, amounts); emit TransferSingle(msg.sender, msg.sender, address(0), objectId, amount); } /** * @dev Burn Batch * Same as burn, but for multiple NFTs at the same time */ function burnBatch( uint256[] memory objectIds, uint256[] memory amounts ) public virtual override { _burn(msg.sender, objectIds, amounts); emit TransferBatch(msg.sender, msg.sender, address(0), objectIds, amounts); } function _burn(address owner, uint256[] memory objectIds, uint256[] memory amounts) internal virtual { for (uint256 i = 0; i < objectIds.length; i++) { asERC20(objectIds[i]).burn( owner, toERC20WrapperAmount(objectIds[i], amounts[i]) ); } } /** * @dev get the address of the ERC20 Contract used as a model */ function erc20NFTWrapperModel() public virtual override view returns (address) { return _erc20NFTWrapperModel; } /** * @dev Gives back the address of the ERC20 Token representing this Token Id */ function asERC20(uint256 objectId) public virtual override view returns (IERC20NFTWrapper) { return IERC20NFTWrapper(_dest[objectId]); } /** * @dev Returns the total supply of the given token id * @param objectId the id of the token whose availability you want to know */ function totalSupply(uint256 objectId) public virtual override view returns (uint256) { return toEthItemAmount(objectId, asERC20(objectId).totalSupply()); } /** * @dev Returns the name of the given token id * @param objectId the id of the token whose name you want to know */ function name(uint256 objectId) public virtual override view returns (string memory) { return asERC20(objectId).name(); } function name() public virtual override view returns (string memory) { return _name; } /** * @dev Returns the symbol of the given token id * @param objectId the id of the token whose symbol you want to know */ function symbol(uint256 objectId) public virtual override view returns (string memory) { return asERC20(objectId).symbol(); } function symbol() public virtual override view returns (string memory) { return _symbol; } /** * @dev Returns the decimals of the given token id */ function decimals(uint256) public virtual override view returns (uint256) { return 1; } /** * @dev Returns the uri of the given token id * @param objectId the id of the token whose uri you want to know */ function uri(uint256 objectId) public virtual override view returns (string memory) { return _objectUris[objectId]; } /** * @dev Classic ERC1155 Standard Method */ function balanceOf(address account, uint256 objectId) public virtual override view returns (uint256) { return toEthItemAmount(objectId, asERC20(objectId).balanceOf(account)); } /** * @dev Classic ERC1155 Standard Method */ function balanceOfBatch( address[] memory accounts, uint256[] memory objectIds ) public virtual override view returns (uint256[] memory balances) { balances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; i++) { balances[i] = balanceOf(accounts[i], objectIds[i]); } } /** * @dev Classic ERC1155 Standard Method */ function setApprovalForAll(address operator, bool approved) public virtual override { address sender = _msgSender(); require( sender != operator, "ERC1155: setting approval status for self" ); _operatorApprovals[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /** * @dev Classic ERC1155 Standard Method */ function isApprovedForAll(address account, address operator) public virtual override view returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev Classic ERC1155 Standard Method */ function safeTransferFrom( address from, address to, uint256 objectId, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); require( from == operator || isApprovedForAll(from, operator), "ERC1155: caller is not owner nor approved" ); asERC20(objectId).transferFrom(from, to, toERC20WrapperAmount(objectId, amount)); emit TransferSingle(operator, from, to, objectId, amount); _doSafeTransferAcceptanceCheck( operator, from, to, objectId, amount, data ); } /** * @dev Classic ERC1155 Standard Method */ function safeBatchTransferFrom( address from, address to, uint256[] memory objectIds, uint256[] memory amounts, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); for (uint256 i = 0; i < objectIds.length; i++) { asERC20(objectIds[i]).transferFrom( from, to, toERC20WrapperAmount(objectIds[i], amounts[i]) ); } address operator = _msgSender(); emit TransferBatch(operator, from, to, objectIds, amounts); _doSafeBatchTransferAcceptanceCheck( operator, from, to, objectIds, amounts, data ); } function emitTransferSingleEvent(address sender, address from, address to, uint256 objectId, uint256 amount) public override { require(_dest[objectId] == msg.sender, "Unauthorized Action!"); uint256 entireAmount = toEthItemAmount(objectId, amount); if(entireAmount == 0) { return; } emit TransferSingle(sender, from, to, objectId, entireAmount); } function toERC20WrapperAmount(uint256 objectId, uint256 ethItemAmount) public override virtual view returns (uint256 erc20WrapperAmount) { erc20WrapperAmount = ethItemAmount * (10**asERC20(objectId).decimals()); } function toEthItemAmount(uint256 objectId, uint256 erc20WrapperAmount) public override virtual view returns (uint256 ethItemAmount) { ethItemAmount = erc20WrapperAmount / (10**asERC20(objectId).decimals()); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if ( response != IERC1155Receiver(to).onERC1155Received.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver(to).onERC1155BatchReceived.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _clone(address original) internal returns (address copy) { assembly { mstore( 0, or( 0x5880730000000000000000000000000000000000000000803b80938091923cF3, mul(original, 0x1000000000000000000) ) ) copy := create(0, 0, 32) switch extcodesize(copy) case 0 { invalid() } } } function _mint( address from, uint256 amount ) internal virtual returns (uint256 objectId, address wrapperAddress) { IERC20NFTWrapper wrapper = IERC20NFTWrapper(wrapperAddress = _clone(erc20NFTWrapperModel())); _isMine[_dest[objectId = uint256(wrapperAddress)] = wrapperAddress] = true; wrapper.init(objectId, _name, _symbol, _decimals); wrapper.mint(from, amount * (10**_decimals)); emit Mint(objectId, wrapperAddress, amount); emit TransferSingle(address(this), address(0), from, objectId, amount); } } // File: orchestrator\IEthItemOrchestratorDependantElement.sol //SPDX_License_Identifier: MIT pragma solidity ^0.6.0; interface IEthItemOrchestratorDependantElement is IERC165 { /** * @dev GET - The DoubleProxy of the DFO linked to this Contract */ function doubleProxy() external view returns (address); /** * @dev SET - The DoubleProxy of the DFO linked to this Contract * It can be done only by the Factory controller * @param newDoubleProxy the new DoubleProxy address */ function setDoubleProxy(address newDoubleProxy) external; function isAuthorizedOrchestrator(address operator) external view returns(bool); } // File: factory\IEthItemFactory.sol //SPDX_License_Identifier: MIT pragma solidity ^0.6.0; /** * @title IEthItemFactory * @dev This contract represents the Factory Used to deploy all the EthItems, keeping track of them. */ interface IEthItemFactory is IEthItemOrchestratorDependantElement { /** * @dev GET - The address of the Smart Contract whose code will serve as a model for all the EthItemERC20Wrappers (please see the eth-item-token-standard for further information). */ function ethItemERC20WrapperModel() external view returns (address ethItemERC20WrapperModelAddress); /** * @dev SET - The address of the Smart Contract whose code will serve as a model for all the EthItemERC20Wrappers (please see the eth-item-token-standard for further information). * It can be done only by the Factory controller */ function setEthItemERC20WrapperModel(address ethItemERC20WrapperModelAddress) external; /** * @dev GET - The address of the Smart Contract whose code will serve as a model for all the ERC1155 NFT-Based EthItems. * Every EthItem will have its own address, but the code will be cloned from this one. */ function erc1155Model() external view returns (address erc1155ModelAddress, uint256 erc1155ModelVersion); /** * @dev SET - The address of the ERC1155 NFT-Based EthItem model. * It can be done only by the Factory controller */ function setERC1155Model(address erc1155ModelAddress) external; /** * @dev GET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC1155 EthItems. * Every EthItem will have its own address, but the code will be cloned from this one. */ function erc1155WrapperModel() external view returns (address erc1155WrapperModelAddress, uint256 erc1155WrapperModelVersion); /** * @dev SET - The address of the ERC1155 NFT-Based EthItem model. * It can be done only by the Factory controller */ function setERC1155WrapperModel(address erc1155WrapperModelAddress) external; /** * @dev GET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC20 EthItems. */ function erc20WrapperModel() external view returns (address erc20WrapperModelAddress, uint256 erc20WrapperModelVersion); /** * @dev SET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC20 EthItems. * It can be done only by the Factory controller */ function setERC20WrapperModel(address erc20WrapperModelAddress) external; /** * @dev GET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC721 EthItems. */ function erc721WrapperModel() external view returns (address erc721WrapperModelAddress, uint256 erc721WrapperModelVersion); /** * @dev SET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC721 EthItems. * It can be done only by the Factory controller */ function setERC721WrapperModel(address erc721WrapperModelAddress) external; /** * @dev GET - The elements (numerator and denominator) useful to calculate the percentage fee to be transfered to the DFO for every new Minted EthItem */ function mintFeePercentage() external view returns (uint256 mintFeePercentageNumerator, uint256 mintFeePercentageDenominator); /** * @dev SET - The element useful to calculate the Percentage fee * It can be done only by the Factory controller */ function setMintFeePercentage(uint256 mintFeePercentageNumerator, uint256 mintFeePercentageDenominator) external; /** * @dev Useful utility method to calculate the percentage fee to transfer to the DFO for the minted EthItem amount. * @param erc20WrapperAmount The amount of minted EthItem */ function calculateMintFee(uint256 erc20WrapperAmount) external view returns (uint256 mintFee, address dfoWalletAddress); /** * @dev GET - The elements (numerator and denominator) useful to calculate the percentage fee to be transfered to the DFO for every Burned EthItem */ function burnFeePercentage() external view returns (uint256 burnFeePercentageNumerator, uint256 burnFeePercentageDenominator); /** * @dev SET - The element useful to calculate the Percentage fee * It can be done only by the Factory controller */ function setBurnFeePercentage(uint256 burnFeePercentageNumerator, uint256 burnFeePercentageDenominator) external; /** * @dev Useful utility method to calculate the percentage fee to transfer to the DFO for the burned EthItem amount. * @param erc20WrapperAmount The amount of burned EthItem */ function calculateBurnFee(uint256 erc20WrapperAmount) external view returns (uint256 burnFee, address dfoWalletAddress); /** * @dev Business Logic to create a brand-new EthItem. * It raises the 'NewERC1155Created' event. * @param modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT. * It changes according to the Model Version. * @param ethItemAddress The address of the new EthItem * @param ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure. */ function createERC1155(bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse); event NewERC1155Created(address indexed model, uint256 indexed modelVersion, address indexed tokenCreated, address creator); /** * @dev Business Logic to wrap already existing ERC1155 Tokens to obtain a new NFT-Based EthItem. * It raises the 'NewWrappedERC1155Created' event. * @param modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT. * It changes according to the Model Version. * @param ethItemAddress The address of the new EthItem * @param ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure. */ function createWrappedERC1155(bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse); event NewWrappedERC1155Created(address indexed model, uint256 indexed modelVersion, address indexed tokenCreated, address creator); /** * @dev Business Logic to wrap already existing ERC20 Tokens to obtain a new NFT-Based EthItem. * It raises the 'NewWrappedERC20Created' event. * @param modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT. * It changes according to the Model Version. * @param ethItemAddress The address of the new EthItem * @param ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure. */ function createWrappedERC20(bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse); event NewWrappedERC20Created(address indexed model, uint256 indexed modelVersion, address indexed tokenCreated, address creator); /** * @dev Business Logic to wrap already existing ERC721 Tokens to obtain a new NFT-Based EthItem. * It raises the 'NewWrappedERC721Created' event. * @param modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT. * It changes according to the Model Version. * @param ethItemAddress The address of the new EthItem * @param ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure. */ function createWrappedERC721(bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse); event NewWrappedERC721Created(address indexed model, uint256 indexed modelVersion, address indexed tokenCreated, address creator); } // File: models\common\EthItemModelBase.sol //SPDX_License_Identifier: MIT pragma solidity ^0.6.0; abstract contract EthItemModelBase is IEthItemModelBase, EthItem(address(0), "", "") { address internal _factoryAddress; function init( address, string memory, string memory ) public virtual override(IEthItem, EthItem) { revert("Cannot directly call this method."); } function init( string memory name, string memory symbol ) public override virtual { require(_factoryAddress == address(0), "Init already called!"); super.init(IEthItemFactory(_factoryAddress = msg.sender).ethItemERC20WrapperModel(), name, symbol); } function modelVersion() public override virtual pure returns(uint256) { return 1; } function factory() public override view returns (address) { return _factoryAddress; } function _sendMintFeeToDFO(address from, uint256 objectId, uint256 erc20WrapperAmount) internal virtual returns(uint256 mintFeeToDFO) { address dfoWallet; (mintFeeToDFO, dfoWallet) = IEthItemFactory(_factoryAddress).calculateMintFee(erc20WrapperAmount); if(mintFeeToDFO > 0 && dfoWallet != address(0)) { asERC20(objectId).transferFrom(from, dfoWallet, mintFeeToDFO); } } function _sendBurnFeeToDFO(address from, uint256 objectId, uint256 erc20WrapperAmount) internal virtual returns(uint256 burnFeeToDFO) { address dfoWallet; (burnFeeToDFO, dfoWallet) = IEthItemFactory(_factoryAddress).calculateBurnFee(erc20WrapperAmount); if(burnFeeToDFO > 0 && dfoWallet != address(0)) { asERC20(objectId).transferFrom(from, dfoWallet, burnFeeToDFO); } } function safeTransferFrom( address from, address to, uint256 objectId, uint256 amount, bytes memory data ) public virtual override(IERC1155, EthItem) { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); require( from == operator || isApprovedForAll(from, operator), "ERC1155: caller is not owner nor approved" ); _doERC20Transfer(from, to, objectId, amount); emit TransferSingle(operator, from, to, objectId, amount); _doSafeTransferAcceptanceCheck( operator, from, to, objectId, amount, data ); } /** * @dev Classic ERC1155 Standard Method */ function safeBatchTransferFrom( address from, address to, uint256[] memory objectIds, uint256[] memory amounts, bytes memory data ) public virtual override(IERC1155, EthItem) { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); for (uint256 i = 0; i < objectIds.length; i++) { _doERC20Transfer(from, to, objectIds[i], amounts[i]); } address operator = _msgSender(); emit TransferBatch(operator, from, to, objectIds, amounts); _doSafeBatchTransferAcceptanceCheck( operator, from, to, objectIds, amounts, data ); } function _doERC20Transfer(address from, address to, uint256 objectId, uint256 amount) internal virtual { (,uint256 result) = _getCorrectERC20ValueForTransferOrBurn(from, objectId, amount); asERC20(objectId).transferFrom(from, to, result); } function _getCorrectERC20ValueForTransferOrBurn(address from, uint256 objectId, uint256 amount) internal virtual view returns(uint256 balanceOfNormal, uint256 result) { uint256 toTransfer = toERC20WrapperAmount(objectId, amount); uint256 balanceOfDecimals = asERC20(objectId).balanceOf(from); balanceOfNormal = balanceOf(from, objectId); result = amount == balanceOfNormal ? balanceOfDecimals : toTransfer; } function _burn( uint256 objectId, uint256 amount ) internal virtual returns(uint256 burnt) { (uint256 balanceOfNormal, uint256 result) = _getCorrectERC20ValueForTransferOrBurn(msg.sender, objectId, amount); require(balanceOfNormal >= amount, "Insufficient Amount"); uint256 burnFeeToDFO = _sendBurnFeeToDFO(msg.sender, objectId, result); asERC20(objectId).burn(msg.sender, burnt = result - burnFeeToDFO); } } // File: models\ERC1155\1\ERC1155V1.sol //SPDX_License_Identifier: MIT pragma solidity ^0.6.0; contract ERC1155V1 is IERC1155V1, EthItemModelBase { address internal _extensionAddress; bool internal _keepMint; function init(string memory name, string memory symbol, address extensionAddress, bytes memory extensionInitPayload) public override virtual returns(bytes memory extensionInitCallResponse) { super.init(name, symbol); extensionInitCallResponse = _initExtension(extensionAddress, extensionInitPayload); _keepMint = _extensionAddress == address(0); } function _initExtension(address extensionAddress, bytes memory extensionInitPayload) internal virtual returns(bytes memory extensionInitCallResponse) { _extensionAddress = extensionAddress; if ( extensionAddress != address(0) && keccak256(extensionInitPayload) != keccak256("") ) { bool extensionInitCallResult = false; ( extensionInitCallResult, extensionInitCallResponse ) = extensionAddress.call(extensionInitPayload); require( extensionInitCallResult, "Extension Init Call Result failed!" ); } } function extension() public view virtual override returns (address) { return _extensionAddress; } function canMint(address operator) public view virtual override returns (bool result) { result = operator == _extensionAddress || (_extensionAddress == address(0) && _keepMint); } function balanceOf(address account, uint256 objectId) public virtual override view returns (uint256) { (bool unique, uint256 unity,, uint256 erc20Decimals) = _isUnique(objectId); uint256 accountBalance = asERC20(objectId).balanceOf(account); if(unique) { uint256 max = (unity * 51) / 100; return accountBalance > max ? 1 : 0; } return (accountBalance / (10**erc20Decimals)); } function mint(uint256 amount, string memory objectUri) public virtual override returns (uint256 objectId, address tokenAddress) { require(canMint(msg.sender), "Unauthorized action!"); require( keccak256(bytes(objectUri)) != keccak256(""), "Uri cannot be empty" ); (objectId, tokenAddress) = _mint(msg.sender, amount); _objectUris[objectId] = objectUri; _sendMintFeeToDFO(msg.sender, objectId, toERC20WrapperAmount(objectId, amount)); } function burn( uint256 objectId, uint256 amount ) public virtual override { _burn(objectId, amount); emit TransferSingle(msg.sender, msg.sender, address(0), objectId, amount); } function burnBatch( uint256[] memory objectIds, uint256[] memory amounts ) public virtual override { for (uint256 i = 0; i < objectIds.length; i++) { _burn(objectIds[i], amounts[i]); } emit TransferBatch(msg.sender, msg.sender, address(0), objectIds, amounts); } function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { if(operator == _extensionAddress) { return true; } return super.isApprovedForAll(account, operator); } function releaseExtension(bool keepMint) public override { require(msg.sender == _extensionAddress, "Unauthorized Action!"); _keepMint = keepMint; _extensionAddress = address(0); } function _isUnique(uint256 objectId) internal view returns (bool unique, uint256 unity, uint256 totalSupply, uint256 erc20Decimals) { erc20Decimals = asERC20(objectId).decimals(); unity = erc20Decimals == 1 ? 1 : (10**erc20Decimals); totalSupply = asERC20(objectId).totalSupply(); if(totalSupply == 0) { unique = true; } else { unique = totalSupply <= unity; } } }
Classic ERC1155 Standard Method/
function safeBatchTransferFrom( address from, address to, uint256[] memory objectIds, uint256[] memory amounts, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); for (uint256 i = 0; i < objectIds.length; i++) { asERC20(objectIds[i]).transferFrom( from, to, toERC20WrapperAmount(objectIds[i], amounts[i]) ); } address operator = _msgSender(); emit TransferBatch(operator, from, to, objectIds, amounts); _doSafeBatchTransferAcceptanceCheck( operator, from, to, objectIds, amounts, data ); }
320,525
./full_match/137/0x9Bb4627884A2aDAA2578C3BD81Fc3D88c8248271/sources/contracts/FlashloanQuickswap.sol
recheck for stopping and gas usage
function start( uint _maxBlockNumber, address _sourceRouter, address _targetRouter, address _sourceFactory ) external { require(block.number <= _maxBlockNumber, 'e00'); (int256 profit, uint256 _tokenBorrowAmount) = check(_tokenBorrow, _amountTokenPay, _tokenPay, _sourceRouter, _targetRouter); require(profit > 0, 'e01'); require(pairAddress != address(0), 'e10'); address token0 = IUniswapV2Pair(pairAddress).token0(); address token1 = IUniswapV2Pair(pairAddress).token1(); require(token0 != address(0) && token1 != address(0), 'e11'); IUniswapV2Pair(pairAddress).swap( _tokenBorrow == token0 ? _tokenBorrowAmount : 0, _tokenBorrow == token1 ? _tokenBorrowAmount : 0, address(this), abi.encode(_sourceRouter, _targetRouter) ); }
3,747,621
pragma solidity >= 0.6.0; // Interface of the contract we want to interact with. abstract contract IBounceCallee { function receiveMoney(uint128 value) public payable virtual; function receiveValues(uint16 value1, bool value2, uint64 value3) public virtual; } // Contract that can handle errors during intercontract communication. contract BounceCaller { // State variables: uint bounceCounter; // Number of onBounce function calls; // Saved arguments of function calls which were handled with failure. uint16 invalidValue1; bool invalidValue2; uint64 invalidValue3; uint128 invalidMoneyAmount; modifier alwaysAccept { tvm.accept(); _; } // Function onBounce is executed on inbound messages with set <bounced> flag. // This function takes the body of the message as an argument. onBounce(TvmSlice slice) external { // Increase the counter. bounceCounter++; // Start decoding the message. First 32 bits store the function id. uint32 functionId = slice.decode(uint32); // Api function tvm.functionId() allows to calculate function id by function name. if (functionId == tvm.functionId(IBounceCallee.receiveMoney)) { //Function decodeFunctionParams() allows to decode function parameters from the slice. // After decoding we store the arguments of the function in the state variables. invalidMoneyAmount = slice.decodeFunctionParams(IBounceCallee.receiveMoney); } else if (functionId == tvm.functionId(IBounceCallee.receiveValues)) { (invalidValue1, invalidValue2, invalidValue3) = slice.decodeFunctionParams(IBounceCallee.receiveValues); } } // Function that calls another contract function and attaches some currency to the call. function sendMoney(address callee, uint128 amount) public payable alwaysAccept { IBounceCallee(callee).receiveMoney.value(amount)(amount); } // Funciton that calls another contract function with arbitrary arguments. function sendValues(address callee, uint16 value1, bool value2, uint64 value3) public pure alwaysAccept { IBounceCallee(callee).receiveValues(value1, value2, value3); } // Function to get state variables. function getData() public view alwaysAccept returns (uint, uint16, bool, uint64, uint128) { return (bounceCounter, invalidValue1, invalidValue2, invalidValue3, invalidMoneyAmount); } }
Funciton that calls another contract function with arbitrary arguments.
function sendValues(address callee, uint16 value1, bool value2, uint64 value3) public pure alwaysAccept { IBounceCallee(callee).receiveValues(value1, value2, value3); }
5,375,996
./full_match/1/0x97de57eC338AB5d51557DA3434828C5DbFaDA371/sources/contracts/EUSD.sol
Atomically decreases the allowance granted to `_spender` by the caller by `_subtractedValue`. This is an alternative to `approve` that can be used as a mitigation for problems described in: 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`. - the contract must not be paused./
function decreaseAllowance( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require( currentAllowance >= _subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO" ); _approve(msg.sender, _spender, currentAllowance.sub(_subtractedValue)); return true; }
3,209,248
pragma solidity ^0.4.11; import "../PublicMarket.sol"; import "../Product.sol"; import "../KioskMarketToken.sol"; import "../OrderTracker.sol"; /** * EtherMarket exchanges KMT for ETH. It also sells ETH as a Kiosk Product. */ contract EtherMarket is PublicMarket, Product { // The DIN for ETH uint256 public ETH_DIN; // How many KMT a buyer gets per wei. uint256 public rate = 300; // Order ID => Initial ETH balance of buyer mapping (uint256 => uint256) public initialBalances; // Constructor function EtherMarket(KioskMarketToken _KMT, uint256 _DIN) PublicMarket(_KMT) { ETH_DIN = _DIN; products[_DIN].priceResolver = this; products[_DIN].inventoryResolver = this; products[_DIN].buyHandler = this; } // Get KMT function contribute() payable { // KMT to issue uint256 issuableKMT = msg.value * rate; // Throw if this contract doesn't have enough KMT require(KMT.balanceOf(this) >= issuableKMT); // Transfer KMT to the buyer KMT.transfer(msg.sender, issuableKMT); } // TODO: Add withdraw logic function withdraw() {} function orderData(uint256 DIN, address buyer) constant returns (bytes32) { // You're buying ether in this market. return keccak256(name(DIN)); } // TODO: This should implement some logic to prove it is a fair market. function isFulfilled(uint256 orderID) constant returns (bool) { return true; } // Kiosk Protocol function name(uint256 DIN) constant returns (string) { // require(DIN == ETH_DIN); return "1 Ether (ETH)"; } // Product function totalPrice(uint256 DIN, uint256 quantity, address buyer) constant returns (uint256) { // require(DIN == ETH_DIN); return quantity * rate * 10**18; // 10^18 wei per ether } function isAvailableForSale(uint256 DIN, uint256 quantity) constant returns (bool) { // require(DIN == ETH_DIN); return (this.balance >= quantity); } function handleOrder(uint256 orderID, uint256 DIN, uint256 quantity, address buyer) { // require(DIN == ETH_DIN); uint256 etherQuantity = quantity * 10**18; // Throw if this contract doesn't have enough ETH require (this.balance >= etherQuantity); // Transfer ETH to the buyer buyer.transfer(etherQuantity); } }
Kiosk Protocol require(DIN == ETH_DIN);
function name(uint256 DIN) constant returns (string) { return "1 Ether (ETH)"; }
1,069,236
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./SnapshotDelegatorPCVDeposit.sol"; import "./utils/VoteEscrowTokenManager.sol"; import "./utils/LiquidityGaugeManager.sol"; import "./utils/OZGovernorVoter.sol"; /// @title ANGLE Token PCV Deposit /// @author Fei Protocol contract AngleDelegatorPCVDeposit is SnapshotDelegatorPCVDeposit, VoteEscrowTokenManager, LiquidityGaugeManager, OZGovernorVoter { address private constant ANGLE_TOKEN = 0x31429d1856aD1377A8A0079410B297e1a9e214c2; address private constant ANGLE_VE_TOKEN = 0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5; address private constant ANGLE_GAUGE_MANAGER = 0x9aD7e7b0877582E14c17702EecF49018DD6f2367; bytes32 private constant ANGLE_SNAPSHOT_SPACE = keccak256("anglegovernance.eth"); /// @notice ANGLE token manager /// @param _core Fei Core for reference /// @param _initialDelegate initial delegate for snapshot votes constructor( address _core, address _initialDelegate ) SnapshotDelegatorPCVDeposit( _core, IERC20(ANGLE_TOKEN), // token used in reporting ANGLE_SNAPSHOT_SPACE, // snapshot spaceId _initialDelegate ) VoteEscrowTokenManager( IERC20(ANGLE_TOKEN), // liquid token IVeToken(ANGLE_VE_TOKEN), // vote-escrowed token 4 * 365 * 86400 // vote-escrow time = 4 years ) LiquidityGaugeManager(ANGLE_GAUGE_MANAGER) OZGovernorVoter() {} /// @notice returns total balance of PCV in the Deposit function balance() public view override returns (uint256) { return _totalTokensManaged(); // liquid and vote-escrowed tokens } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../core/TribeRoles.sol"; import "../pcv/PCVDeposit.sol"; interface DelegateRegistry { function setDelegate(bytes32 id, address delegate) external; function clearDelegate(bytes32 id) external; function delegation(address delegator, bytes32 id) external view returns(address delegatee); } /// @title Snapshot Delegator PCV Deposit /// @author Fei Protocol contract SnapshotDelegatorPCVDeposit is PCVDeposit { event DelegateUpdate(address indexed oldDelegate, address indexed newDelegate); /// @notice the Gnosis delegate registry used by snapshot DelegateRegistry public constant DELEGATE_REGISTRY = DelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); /// @notice the token that is being used for snapshot IERC20 public immutable token; /// @notice the keccak encoded spaceId of the snapshot space bytes32 public spaceId; /// @notice the snapshot delegate for the deposit address public delegate; /// @notice Snapshot Delegator PCV Deposit constructor /// @param _core Fei Core for reference /// @param _token snapshot token /// @param _spaceId the id (or ENS name) of the snapshot space constructor( address _core, IERC20 _token, bytes32 _spaceId, address _initialDelegate ) CoreRef(_core) { token = _token; spaceId = _spaceId; _delegate(_initialDelegate); } /// @notice withdraw tokens from the PCV allocation /// @param amountUnderlying of tokens withdrawn /// @param to the address to send PCV to function withdraw(address to, uint256 amountUnderlying) external override onlyPCVController { _withdrawERC20(address(token), to, amountUnderlying); } /// @notice no-op function deposit() external override {} /// @notice returns total balance of PCV in the Deposit function balance() public view virtual override returns (uint256) { return token.balanceOf(address(this)); } /// @notice display the related token of the balance reported function balanceReportedIn() public view override returns (address) { return address(token); } /// @notice sets the snapshot space ID function setSpaceId(bytes32 _spaceId) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) { spaceId = _spaceId; } /// @notice sets the snapshot delegate function setDelegate(address newDelegate) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) { _delegate(newDelegate); } /// @notice clears the delegate from snapshot function clearDelegate() external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) { address oldDelegate = delegate; DELEGATE_REGISTRY.clearDelegate(spaceId); emit DelegateUpdate(oldDelegate, address(0)); } function _delegate(address newDelegate) internal { address oldDelegate = delegate; DELEGATE_REGISTRY.setDelegate(spaceId, newDelegate); delegate = newDelegate; emit DelegateUpdate(oldDelegate, newDelegate); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /** @title Tribe DAO ACL Roles @notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO. Roles are broken up into 3 categories: * Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed. * Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms * Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs. */ library TribeRoles { /*/////////////////////////////////////////////////////////////// Major Roles //////////////////////////////////////////////////////////////*/ /// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality. bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE"); /// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE"); /// @notice the role which can arbitrarily move PCV in any size from any contract bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE"); /// @notice can mint FEI arbitrarily bytes32 internal constant MINTER = keccak256("MINTER_ROLE"); /*/////////////////////////////////////////////////////////////// Admin Roles //////////////////////////////////////////////////////////////*/ /// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE. bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN"); /// @notice manages the Collateralization Oracle as well as other protocol oracles. bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE"); /// @notice manages TribalChief incentives and related functionality. bytes32 internal constant TRIBAL_CHIEF_ADMIN = keccak256("TRIBAL_CHIEF_ADMIN_ROLE"); /// @notice admin of PCVGuardian bytes32 internal constant PCV_GUARDIAN_ADMIN = keccak256("PCV_GUARDIAN_ADMIN_ROLE"); /// @notice admin of all Minor Roles bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN"); /// @notice admin of the Fuse protocol bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN"); /// @notice capable of vetoing DAO votes or optimistic timelocks bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN"); /// @notice capable of setting FEI Minters within global rate limits and caps bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN"); /// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN"); /// @notice manages meta-governance actions, like voting & delegating. /// Also used to vote for gauge weights & similar liquid governance things. bytes32 internal constant METAGOVERNANCE_VOTE_ADMIN = keccak256("METAGOVERNANCE_VOTE_ADMIN"); /// @notice allows to manage locking of vote-escrowed tokens, and staking/unstaking /// governance tokens from a pre-defined contract in order to eventually allow voting. /// Examples: ANGLE <> veANGLE, AAVE <> stkAAVE, CVX <> vlCVX, CRV > cvxCRV. bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING"); /// @notice manages whitelisting of gauges where the protocol's tokens can be staked bytes32 internal constant METAGOVERNANCE_GAUGE_ADMIN = keccak256("METAGOVERNANCE_GAUGE_ADMIN"); /// @notice manages staking to & unstaking from gauges of the protocol's tokens bytes32 internal constant METAGOVERNANCE_GAUGE_STAKING = keccak256("METAGOVERNANCE_GAUGE_STAKING"); /*/////////////////////////////////////////////////////////////// Minor Roles //////////////////////////////////////////////////////////////*/ /// @notice capable of poking existing LBP auctions to exchange tokens. bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE"); /// @notice capable of engaging with Votium for voting incentives. bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE"); /// @notice capable of changing parameters within non-critical ranges bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE"); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; import "./IPCVDeposit.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller /// @author Fei Protocol abstract contract PCVDeposit is IPCVDeposit, CoreRef { using SafeERC20 for IERC20; /// @notice withdraw ERC20 from the contract /// @param token address of the ERC20 to send /// @param to address destination of the ERC20 /// @param amount quantity of ERC20 to send function withdrawERC20( address token, address to, uint256 amount ) public virtual override onlyPCVController { _withdrawERC20(token, to, amount); } function _withdrawERC20( address token, address to, uint256 amount ) internal { IERC20(token).safeTransfer(to, amount); emit WithdrawERC20(msg.sender, token, to, amount); } /// @notice withdraw ETH from the contract /// @param to address to send ETH /// @param amountOut amount of ETH to send function withdrawETH(address payable to, uint256 amountOut) external virtual override onlyPCVController { Address.sendValue(to, amountOut); emit WithdrawETH(msg.sender, to, amountOut); } function balance() public view virtual override returns(uint256); function resistantBalanceAndFei() public view virtual override returns(uint256, uint256) { return (balance(), 0); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private immutable _core; IFei private immutable _fei; IERC20 private immutable _tribe; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; constructor(address coreAddress) { _core = ICore(coreAddress); _fei = ICore(coreAddress).fei(); _tribe = ICore(coreAddress).tribe(); _setContractAdminRole(ICore(coreAddress).GOVERN_ROLE()); } function _initialize(address) internal {} // no-op for backward compatibility modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier isGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin"); _; } // Named onlyTribeRole to prevent collision with OZ onlyRole modifier modifier onlyTribeRole(bytes32 role) { require(_core.hasRole(role, msg.sender), "UNAUTHORIZED"); _; } // Modifiers to allow any combination of roles modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfThreeRoles(bytes32 role1, bytes32 role2, bytes32 role3) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfFourRoles(bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfFiveRoles(bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED"); _; } modifier onlyFei() { require(msg.sender == address(_fei), "CoreRef: Caller is not FEI"); _; } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _fei; } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _tribe; } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return _fei.balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return _tribe.balanceOf(address(this)); } function _burnFeiHeld() internal { _fei.burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { _fei.mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../fei/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPCVDepositBalances.sol"; /// @title a PCV Deposit interface /// @author Fei Protocol interface IPCVDeposit is IPCVDepositBalances { // ----------- Events ----------- event Deposit(address indexed _from, uint256 _amount); event Withdrawal( address indexed _caller, address indexed _to, uint256 _amount ); event WithdrawERC20( address indexed _caller, address indexed _token, address indexed _to, uint256 _amount ); event WithdrawETH( address indexed _caller, address indexed _to, uint256 _amount ); // ----------- State changing api ----------- function deposit() external; // ----------- PCV Controller only state changing api ----------- function withdraw(address to, uint256 amount) external; function withdrawERC20(address token, address to, uint256 amount) external; function withdrawETH(address payable to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title a PCV Deposit interface for only balance getters /// @author Fei Protocol interface IPCVDepositBalances { // ----------- Getters ----------- /// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn function balance() external view returns (uint256); /// @notice gets the token address in which this deposit returns its balance function balanceReportedIn() external view returns (address); /// @notice gets the resistant token balance and protocol owned fei of this deposit function resistantBalanceAndFei() external view returns (uint256, uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../refs/CoreRef.sol"; import "../../core/TribeRoles.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVeToken { function balanceOf(address) external view returns (uint256); function locked(address) external view returns (uint256); function create_lock(uint256 value, uint256 unlock_time) external; function increase_amount(uint256 value) external; function increase_unlock_time(uint256 unlock_time) external; function withdraw() external; function locked__end(address) external view returns (uint256); function checkpoint() external; } /// @title Vote-escrowed Token Manager /// Used to permanently lock tokens in a vote-escrow contract, and refresh /// the lock duration as needed. /// @author Fei Protocol abstract contract VoteEscrowTokenManager is CoreRef { // Events event Lock(uint256 cummulativeTokensLocked, uint256 lockHorizon); event Unlock(uint256 tokensUnlocked); /// @notice One week, in seconds. Vote-locking is rounded down to weeks. uint256 private constant WEEK = 7 * 86400; // 1 week, in seconds /// @notice The lock duration of veTokens uint256 public lockDuration; /// @notice The vote-escrowed token address IVeToken public immutable veToken; /// @notice The token address IERC20 public immutable liquidToken; /// @notice VoteEscrowTokenManager token Snapshot Delegator PCV Deposit constructor /// @param _liquidToken the token to lock for vote-escrow /// @param _veToken the vote-escrowed token used in governance /// @param _lockDuration amount of time (in seconds) tokens will be vote-escrowed for constructor( IERC20 _liquidToken, IVeToken _veToken, uint256 _lockDuration ) { liquidToken = _liquidToken; veToken = _veToken; lockDuration = _lockDuration; } /// @notice Set the amount of time tokens will be vote-escrowed for in lock() calls function setLockDuration(uint256 newLockDuration) external onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) { lockDuration = newLockDuration; } /// @notice Deposit tokens to get veTokens. Set lock duration to lockDuration. /// The only way to withdraw tokens will be to pause this contract /// for lockDuration and then call exitLock(). function lock() external whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) { uint256 tokenBalance = liquidToken.balanceOf(address(this)); uint256 locked = veToken.locked(address(this)); uint256 lockHorizon = ((block.timestamp + lockDuration) / WEEK) * WEEK; // First lock if (tokenBalance != 0 && locked == 0) { liquidToken.approve(address(veToken), tokenBalance); veToken.create_lock(tokenBalance, lockHorizon); } // Increase amount of tokens locked & refresh duration to lockDuration else if (tokenBalance != 0 && locked != 0) { liquidToken.approve(address(veToken), tokenBalance); veToken.increase_amount(tokenBalance); if (veToken.locked__end(address(this)) != lockHorizon) { veToken.increase_unlock_time(lockHorizon); } } // No additional tokens to lock, just refresh duration to lockDuration else if (tokenBalance == 0 && locked != 0) { veToken.increase_unlock_time(lockHorizon); } // If tokenBalance == 0 and locked == 0, there is nothing to do. emit Lock(tokenBalance + locked, lockHorizon); } /// @notice Exit the veToken lock. For this function to be called and not /// revert, tokens had to be locked previously, and the contract must have /// been paused for lockDuration in order to prevent lock extensions /// by calling lock(). This function will recover tokens on the contract, /// which can then be moved by calling withdraw() as a PCVController if the /// contract is also a PCVDeposit, for instance. function exitLock() external onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) { veToken.withdraw(); emit Unlock(liquidToken.balanceOf(address(this))); } /// @notice returns total balance of tokens, vote-escrowed or liquid. function _totalTokensManaged() internal view returns (uint256) { return liquidToken.balanceOf(address(this)) + veToken.locked(address(this)); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../refs/CoreRef.sol"; import "../../core/TribeRoles.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ILiquidityGauge { function deposit(uint256 value) external; function withdraw(uint256 value, bool claim_rewards) external; function claim_rewards() external; function balanceOf(address) external view returns(uint256); function staking_token() external view returns(address); function reward_tokens(uint256 i) external view returns (address token); function reward_count() external view returns (uint256 nTokens); } interface ILiquidityGaugeController { function vote_for_gauge_weights(address gauge_addr, uint256 user_weight) external; function last_user_vote(address user, address gauge) external view returns(uint256); function vote_user_power(address user) external view returns(uint256); function gauge_types(address gauge) external view returns(int128); } /// @title Liquidity gauge manager, used to stake tokens in liquidity gauges. /// @author Fei Protocol abstract contract LiquidityGaugeManager is CoreRef { // Events event GaugeControllerChanged(address indexed oldController, address indexed newController); event GaugeSetForToken(address indexed token, address indexed gauge); event GaugeVote(address indexed gauge, uint256 amount); event GaugeStake(address indexed gauge, uint256 amount); event GaugeUnstake(address indexed gauge, uint256 amount); event GaugeRewardsClaimed(address indexed gauge, address indexed token, uint256 amount); /// @notice address of the gauge controller used for voting address public gaugeController; /// @notice mapping of token staked to gauge address mapping(address=>address) public tokenToGauge; constructor(address _gaugeController) { gaugeController = _gaugeController; } /// @notice Set the gauge controller used for gauge weight voting /// @param _gaugeController the gauge controller address function setGaugeController(address _gaugeController) public onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) { require(gaugeController != _gaugeController, "LiquidityGaugeManager: same controller"); address oldController = gaugeController; gaugeController = _gaugeController; emit GaugeControllerChanged(oldController, gaugeController); } /// @notice Set gauge for a given token. /// @param token the token address to stake in gauge /// @param gaugeAddress the address of the gauge where to stake token function setTokenToGauge( address token, address gaugeAddress ) public onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) { require(ILiquidityGauge(gaugeAddress).staking_token() == token, "LiquidityGaugeManager: wrong gauge for token"); require(ILiquidityGaugeController(gaugeController).gauge_types(gaugeAddress) >= 0, "LiquidityGaugeManager: wrong gauge address"); tokenToGauge[token] = gaugeAddress; emit GaugeSetForToken(token, gaugeAddress); } /// @notice Vote for a gauge's weight /// @param token the address of the token to vote for /// @param gaugeWeight the weight of gaugeAddress in basis points [0, 10_000] function voteForGaugeWeight( address token, uint256 gaugeWeight ) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) { address gaugeAddress = tokenToGauge[token]; require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured"); ILiquidityGaugeController(gaugeController).vote_for_gauge_weights(gaugeAddress, gaugeWeight); emit GaugeVote(gaugeAddress, gaugeWeight); } /// @notice Stake tokens in a gauge /// @param token the address of the token to stake in the gauge /// @param amount the amount of tokens to stake in the gauge function stakeInGauge( address token, uint256 amount ) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) { address gaugeAddress = tokenToGauge[token]; require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured"); IERC20(token).approve(gaugeAddress, amount); ILiquidityGauge(gaugeAddress).deposit(amount); emit GaugeStake(gaugeAddress, amount); } /// @notice Stake all tokens held in a gauge /// @param token the address of the token to stake in the gauge function stakeAllInGauge(address token) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) { address gaugeAddress = tokenToGauge[token]; require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured"); uint256 amount = IERC20(token).balanceOf(address(this)); IERC20(token).approve(gaugeAddress, amount); ILiquidityGauge(gaugeAddress).deposit(amount); emit GaugeStake(gaugeAddress, amount); } /// @notice Unstake tokens from a gauge /// @param token the address of the token to unstake from the gauge /// @param amount the amount of tokens to unstake from the gauge function unstakeFromGauge( address token, uint256 amount ) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) { address gaugeAddress = tokenToGauge[token]; require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured"); ILiquidityGauge(gaugeAddress).withdraw(amount, false); emit GaugeUnstake(gaugeAddress, amount); } /// @notice Claim rewards associated to a gauge where this contract stakes /// tokens. function claimGaugeRewards(address gaugeAddress) public whenNotPaused { uint256 nTokens = ILiquidityGauge(gaugeAddress).reward_count(); address[] memory tokens = new address[](nTokens); uint256[] memory amounts = new uint256[](nTokens); for (uint256 i = 0; i < nTokens; i++) { tokens[i] = ILiquidityGauge(gaugeAddress).reward_tokens(i); amounts[i] = IERC20(tokens[i]).balanceOf(address(this)); } ILiquidityGauge(gaugeAddress).claim_rewards(); for (uint256 i = 0; i < nTokens; i++) { amounts[i] = IERC20(tokens[i]).balanceOf(address(this)) - amounts[i]; emit GaugeRewardsClaimed(gaugeAddress, tokens[i], amounts[i]); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../refs/CoreRef.sol"; import "../../core/TribeRoles.sol"; interface IOZGovernor { function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) external returns (uint256 proposalId); function castVote(uint256 proposalId, uint8 support) external returns (uint256 weight); function state(uint256 proposalId) external view returns (uint256); } /// @title Abstract class to interact with an OZ governor. /// @author Fei Protocol abstract contract OZGovernorVoter is CoreRef { // Events event Proposed(IOZGovernor indexed governor, uint256 proposalId); event Voted(IOZGovernor indexed governor, uint256 proposalId, uint256 weight, uint8 support); /// @notice propose a new proposal on the target governor. function propose( IOZGovernor governor, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) returns (uint256) { uint256 proposalId = governor.propose(targets, values, calldatas, description); emit Proposed(governor, proposalId); return proposalId; } /// @notice cast a vote on a given proposal on the target governor. function castVote( IOZGovernor governor, uint256 proposalId, uint8 support ) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) returns (uint256) { uint256 weight = governor.castVote(proposalId, support); emit Voted(governor, proposalId, weight, support); return weight; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // 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 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been 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()); } } } // 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 IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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); }
display the related token of the balance reported
function balanceReportedIn() public view override returns (address) { return address(token); }
602,809
/** *Submitted for verification at Etherscan.io on 2021-02-11 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/Owned.sol pragma solidity 0.6.12; // Requried one small change in openzeppelin version of ownable, so imported // source code here. Notice line 26 for change. /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { /** * @dev Changed _owner from 'private' to 'internal' */ address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Contract module extends Ownable and provide a way for safe transfer ownership. * New owner has to call acceptOwnership in order to complete ownership trasnfer. */ contract Owned is Ownable { address private _newOwner; /** * @dev Initiate transfer ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. Current owner will still be owner until * new owner accept ownership. * @param newOwner new owner address */ function transferOwnership(address newOwner) public override onlyOwner { require(newOwner != address(0), "New owner is the zero address"); _newOwner = newOwner; } /** * @dev Allows new owner to accept ownership of the contract. */ function acceptOwnership() public { require(msg.sender == _newOwner, "Caller is not the new owner"); emit OwnershipTransferred(_owner, _newOwner); _owner = _newOwner; _newOwner = address(0); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/governor/VSPGovernanceToken.sol // From https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pragma solidity 0.6.12; // solhint-disable reason-string, no-empty-blocks abstract contract VSPGovernanceToken is ERC20 { /// @dev A record of each accounts delegate mapping(address => address) public delegates; /// @dev A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @dev A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @dev The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @dev The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /// @dev 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)"); /// @dev A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @dev An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @dev An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * @dev Constructor. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) {} /** * @dev 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); } /** * @dev 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, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), keccak256(bytes("1")), 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), "VSP::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VSP::delegateBySig: invalid nonce"); require(now <= expiry, "VSP::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev 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; } /** * @dev 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, uint256 blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VSP::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VSP::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/governor/VSP.sol pragma solidity 0.6.12; // solhint-disable no-empty-blocks contract VSP is VSPGovernanceToken, Owned { /// @dev The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); uint256 internal immutable mintLockPeriod; uint256 internal constant INITIAL_MINT_LIMIT = 10000000 * (10**18); constructor() public VSPGovernanceToken("VesperToken", "VSP") { mintLockPeriod = block.timestamp + (365 days); } /// @dev Mint VSP. Only owner can mint function mint(address _recipient, uint256 _amount) external onlyOwner { require( (totalSupply().add(_amount) <= INITIAL_MINT_LIMIT) || (block.timestamp > mintLockPeriod), "Minting not allowed" ); _mint(_recipient, _amount); _moveDelegates(address(0), delegates[_recipient], _amount); } /// @dev Burn VSP from caller function burn(uint256 _amount) external { _burn(_msgSender(), _amount); _moveDelegates(delegates[_msgSender()], address(0), _amount); } /// @dev Burn VSP from given account. Caller must have proper allowance. function burnFrom(address _account, uint256 _amount) external { uint256 decreasedAllowance = allowance(_account, _msgSender()).sub(_amount, "ERC20: burn amount exceeds allowance"); _approve(_account, _msgSender(), decreasedAllowance); _burn(_account, _amount); _moveDelegates(delegates[_account], address(0), _amount); } /** * @notice Transfer tokens to multiple recipient * @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. * @param bits array of uint * @return true/false */ function multiTransfer(uint256[] memory bits) external returns (bool) { for (uint256 i = 0; i < bits.length; i++) { address a = address(bits[i] >> 96); uint256 amount = bits[i] & ((1 << 96) - 1); require(transfer(a, amount), "Transfer failed"); } return true; } /** * @notice Triggers an approval from owner to spends * @param _owner The address to approve from * @param _spender The address to be approved * @param _amount The number of tokens that are approved (2^256-1 means infinite) * @param _deadline 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 permit( address _owner, address _spender, uint256 _amount, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external { require(_deadline >= block.timestamp, "VSP:permit: signature expired"); bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), keccak256(bytes("1")), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(PERMIT_TYPEHASH, _owner, _spender, _amount, nonces[_owner]++, _deadline) ); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, _v, _r, _s); require(signatory != address(0) && signatory == _owner, "VSP::permit: invalid signature"); _approve(_owner, _spender, _amount); } /// @dev Overridden ERC20 transfer function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); _moveDelegates(delegates[_msgSender()], delegates[recipient], amount); return true; } /// @dev Overridden ERC20 transferFrom function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), allowance(sender, _msgSender()).sub( amount, "VSP::transferFrom: transfer amount exceeds allowance" ) ); _moveDelegates(delegates[sender], delegates[recipient], amount); return true; } }
Overridden ERC20 transferFrom
function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), allowance(sender, _msgSender()).sub( amount, "VSP::transferFrom: transfer amount exceeds allowance" ) ); _moveDelegates(delegates[sender], delegates[recipient], amount); return true; }
14,984,388
pragma solidity ^0.4.18; 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) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract 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); function resetTimer(string _kingdomKey); } contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Destructible is Ownable { function Destructible() public payable { } function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract ReentrancyGuard { bool private reentrancy_lock = false; modifier nonReentrant() { require(!reentrancy_lock); reentrancy_lock = true; _; reentrancy_lock = false; } } contract Map is PullPayment, Destructible, ReentrancyGuard { using SafeMath for uint256; // STRUCTS struct Transaction { string kingdomKey; address compensationAddress; uint buyingPrice; uint compensation; uint jackpotContribution; uint date; } struct Kingdom { string title; string key; uint kingdomTier; uint kingdomType; uint minimumPrice; uint lastTransaction; uint transactionCount; uint returnPrice; address owner; bool locked; } struct Jackpot { address winner; uint balance; } // struct RoundPoints { // mapping(address => uint) points; // } struct Round { Jackpot jackpot1; Jackpot jackpot2; Jackpot jackpot3; Jackpot jackpot4; Jackpot jackpot5; mapping(string => bool) kingdomsCreated; mapping(address => uint) nbKingdoms; mapping(address => uint) nbTransactions; mapping(address => uint) nbKingdomsType1; mapping(address => uint) nbKingdomsType2; mapping(address => uint) nbKingdomsType3; mapping(address => uint) nbKingdomsType4; mapping(address => uint) nbKingdomsType5; uint startTime; uint endTime; mapping(string => uint) kingdomsKeys; mapping(address => uint) scores; } Kingdom[] public kingdoms; Transaction[] public kingdomTransactions; uint public currentRound; address public bookerAddress; mapping(uint => Round) rounds; mapping(address => uint) lastTransaction; uint constant public ACTION_TAX = 0.02 ether; uint constant public STARTING_CLAIM_PRICE_WEI = 0.03 ether; uint constant MAXIMUM_CLAIM_PRICE_WEI = 800 ether; uint constant KINGDOM_MULTIPLIER = 20; uint constant TEAM_COMMISSION_RATIO = 10; uint constant JACKPOT_COMMISSION_RATIO = 10; // MODIFIERS modifier checkKingdomCap(address _owner, uint _kingdomType) { if (_kingdomType == 1) { require((rounds[currentRound].nbKingdomsType1[_owner] + 1) < 9); } else if (_kingdomType == 2) { require((rounds[currentRound].nbKingdomsType2[_owner] + 1) < 9); } else if (_kingdomType == 3) { require((rounds[currentRound].nbKingdomsType3[_owner] + 1) < 9); } else if (_kingdomType == 4) { require((rounds[currentRound].nbKingdomsType4[_owner] + 1) < 9); } else if (_kingdomType == 5) { require((rounds[currentRound].nbKingdomsType5[_owner] + 1) < 9); } _; } modifier onlyForRemainingKingdoms() { uint remainingKingdoms = getRemainingKingdoms(); require(remainingKingdoms > kingdoms.length); _; } modifier checkKingdomExistence(string key) { require(rounds[currentRound].kingdomsCreated[key] == true); _; } modifier checkIsNotLocked(string kingdomKey) { require(kingdoms[rounds[currentRound].kingdomsKeys[kingdomKey]].locked != true); _; } modifier checkIsClosed() { require(now >= rounds[currentRound].endTime); _; } modifier onlyKingdomOwner(string _key, address _sender) { require (kingdoms[rounds[currentRound].kingdomsKeys[_key]].owner == _sender); _; } // ERC20 address public woodAddress; ERC20Basic woodInterface; // ERC20Basic rock; // ERC20Basic // EVENTS event LandCreatedEvent(string kingdomKey, address monarchAddress); event LandPurchasedEvent(string kingdomKey, address monarchAddress); // // CONTRACT CONSTRUCTOR // function Map(address _bookerAddress, address _woodAddress, uint _startTime, uint _endTime) { bookerAddress = _bookerAddress; woodAddress = _woodAddress; woodInterface = ERC20Basic(_woodAddress); currentRound = 1; rounds[currentRound] = Round(Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), 0, 0); rounds[currentRound].jackpot1 = Jackpot(address(0), 0); rounds[currentRound].jackpot2 = Jackpot(address(0), 0); rounds[currentRound].jackpot3 = Jackpot(address(0), 0); rounds[currentRound].jackpot4 = Jackpot(address(0), 0); rounds[currentRound].jackpot5 = Jackpot(address(0), 0); rounds[currentRound].startTime = _startTime; rounds[currentRound].endTime = _endTime; } function () { } function setWoodAddress (address _woodAddress) public onlyOwner { woodAddress = _woodAddress; woodInterface = ERC20Basic(_woodAddress); } function getRemainingKingdoms() public view returns (uint nb) { for (uint i = 1; i < 8; i++) { if (now < rounds[currentRound].startTime + (i * 12 hours)) { uint result = (10 * i); if (result > 100) { return 100; } else { return result; } } } } // // This is the main function. It is called to buy a kingdom // function purchaseKingdom(string _key, string _title, bool _locked) public payable nonReentrant() checkKingdomExistence(_key) checkIsNotLocked(_key) { require(now < rounds[currentRound].endTime); Round storage round = rounds[currentRound]; uint kingdomId = round.kingdomsKeys[_key]; Kingdom storage kingdom = kingdoms[kingdomId]; require((kingdom.kingdomTier + 1) < 6); uint requiredPrice = kingdom.minimumPrice; if (_locked == true) { requiredPrice = requiredPrice.add(ACTION_TAX); } require (msg.value >= requiredPrice); uint jackpotCommission = (msg.value).sub(kingdom.returnPrice); if (kingdom.returnPrice > 0) { round.nbKingdoms[kingdom.owner]--; if (kingdom.kingdomType == 1) { round.nbKingdomsType1[kingdom.owner]--; } else if (kingdom.kingdomType == 2) { round.nbKingdomsType2[kingdom.owner]--; } else if (kingdom.kingdomType == 3) { round.nbKingdomsType3[kingdom.owner]--; } else if (kingdom.kingdomType == 4) { round.nbKingdomsType4[kingdom.owner]--; } else if (kingdom.kingdomType == 5) { round.nbKingdomsType5[kingdom.owner]--; } compensateLatestMonarch(kingdom.lastTransaction, kingdom.returnPrice); } // woodInterface.resetTimer(_key); kingdom.kingdomTier++; kingdom.title = _title; if (kingdom.kingdomTier == 5) { kingdom.returnPrice = 0; kingdom.minimumPrice = 5 ether; } else if (kingdom.kingdomTier == 2) { kingdom.returnPrice = 0.1125 ether; kingdom.minimumPrice = 0.27 ether; } else if (kingdom.kingdomTier == 3) { kingdom.returnPrice = 0.3375 ether; kingdom.minimumPrice = 0.81 ether; } else if (kingdom.kingdomTier == 4) { kingdom.returnPrice = 1.0125 ether; kingdom.minimumPrice = 2.43 ether; } kingdom.owner = msg.sender; kingdom.locked = _locked; uint transactionId = kingdomTransactions.push(Transaction("", msg.sender, msg.value, 0, jackpotCommission, now)) - 1; kingdomTransactions[transactionId].kingdomKey = _key; kingdom.transactionCount++; kingdom.lastTransaction = transactionId; lastTransaction[msg.sender] = now; setNewJackpot(kingdom.kingdomType, jackpotCommission, msg.sender); LandPurchasedEvent(_key, msg.sender); } function setNewJackpot(uint kingdomType, uint jackpotSplitted, address sender) internal { rounds[currentRound].nbTransactions[sender]++; rounds[currentRound].nbKingdoms[sender]++; if (kingdomType == 1) { rounds[currentRound].nbKingdomsType1[sender]++; rounds[currentRound].jackpot1.balance = rounds[currentRound].jackpot1.balance.add(jackpotSplitted); } else if (kingdomType == 2) { rounds[currentRound].nbKingdomsType2[sender]++; rounds[currentRound].jackpot2.balance = rounds[currentRound].jackpot2.balance.add(jackpotSplitted); } else if (kingdomType == 3) { rounds[currentRound].nbKingdomsType3[sender]++; rounds[currentRound].jackpot3.balance = rounds[currentRound].jackpot3.balance.add(jackpotSplitted); } else if (kingdomType == 4) { rounds[currentRound].nbKingdomsType4[sender]++; rounds[currentRound].jackpot4.balance = rounds[currentRound].jackpot4.balance.add(jackpotSplitted); } else if (kingdomType == 5) { rounds[currentRound].nbKingdomsType5[sender]++; rounds[currentRound].jackpot5.balance = rounds[currentRound].jackpot5.balance.add(jackpotSplitted); } } function setLock(string _key, bool _locked) public payable checkKingdomExistence(_key) onlyKingdomOwner(_key, msg.sender) { if (_locked == true) { require(msg.value >= ACTION_TAX); } kingdoms[rounds[currentRound].kingdomsKeys[_key]].locked = _locked; if (msg.value > 0) { asyncSend(bookerAddress, msg.value); } } function giveKingdom(address owner, string _key, string _title, uint _type) onlyOwner() public { require(_type > 0); require(_type < 6); require(rounds[currentRound].kingdomsCreated[_key] == false); uint kingdomId = kingdoms.push(Kingdom("", "", 1, _type, 0, 0, 1, 0.02 ether, address(0), false)) - 1; kingdoms[kingdomId].title = _title; kingdoms[kingdomId].owner = owner; kingdoms[kingdomId].key = _key; kingdoms[kingdomId].minimumPrice = 0.03 ether; kingdoms[kingdomId].locked = false; rounds[currentRound].kingdomsKeys[_key] = kingdomId; rounds[currentRound].kingdomsCreated[_key] = true; uint transactionId = kingdomTransactions.push(Transaction("", msg.sender, 0.01 ether, 0, 0, now)) - 1; kingdomTransactions[transactionId].kingdomKey = _key; kingdoms[kingdomId].lastTransaction = transactionId; } // // User can call this function to generate new kingdoms (within the limits of available land) // function createKingdom(string _key, string _title, uint _type, bool _locked) checkKingdomCap(msg.sender, _type) onlyForRemainingKingdoms() public payable { require(now < rounds[currentRound].endTime); require(_type > 0); require(_type < 6); uint basePrice = STARTING_CLAIM_PRICE_WEI; uint requiredPrice = basePrice; if (_locked == true) { requiredPrice = requiredPrice.add(ACTION_TAX); } require(msg.value >= requiredPrice); Round storage round = rounds[currentRound]; require(round.kingdomsCreated[_key] == false); uint refundPrice = 0.0375 ether; // (STARTING_CLAIM_PRICE_WEI.mul(125)).div(100); uint nextMinimumPrice = 0.09 ether; // STARTING_CLAIM_PRICE_WEI.add(STARTING_CLAIM_PRICE_WEI.mul(2)); uint kingdomId = kingdoms.push(Kingdom("", "", 1, 0, 0, 0, 1, refundPrice, address(0), false)) - 1; kingdoms[kingdomId].kingdomType = _type; kingdoms[kingdomId].title = _title; kingdoms[kingdomId].owner = msg.sender; kingdoms[kingdomId].key = _key; kingdoms[kingdomId].minimumPrice = nextMinimumPrice; kingdoms[kingdomId].locked = _locked; round.kingdomsKeys[_key] = kingdomId; round.kingdomsCreated[_key] = true; if(_locked == true) { asyncSend(bookerAddress, ACTION_TAX); } uint transactionId = kingdomTransactions.push(Transaction("", msg.sender, msg.value, 0, basePrice, now)) - 1; kingdomTransactions[transactionId].kingdomKey = _key; kingdoms[kingdomId].lastTransaction = transactionId; lastTransaction[msg.sender] = now; setNewJackpot(_type, basePrice, msg.sender); LandCreatedEvent(_key, msg.sender); } // // Send transaction to compensate the previous owner // function compensateLatestMonarch(uint lastTransaction, uint compensationWei) internal { address compensationAddress = kingdomTransactions[lastTransaction].compensationAddress; kingdomTransactions[lastTransaction].compensation = compensationWei; asyncSend(compensationAddress, compensationWei); } // // This function may be useful to force withdraw if user never come back to get his money // function forceWithdrawPayments(address payee) public onlyOwner { uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } function getStartTime() public view returns (uint startTime) { return rounds[currentRound].startTime; } function getEndTime() public view returns (uint endTime) { return rounds[currentRound].endTime; } function payJackpot1() internal checkIsClosed() { address winner = getWinner(1); if (rounds[currentRound].jackpot1.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot1.balance); rounds[currentRound].jackpot1.winner = winner; uint teamComission = (rounds[currentRound].jackpot1.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot1.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot1.balance = 0; } } function payJackpot2() internal checkIsClosed() { address winner = getWinner(2); if (rounds[currentRound].jackpot2.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot2.balance); rounds[currentRound].jackpot2.winner = winner; uint teamComission = (rounds[currentRound].jackpot2.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot2.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot2.balance = 0; } } function payJackpot3() internal checkIsClosed() { address winner = getWinner(3); if (rounds[currentRound].jackpot3.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot3.balance); rounds[currentRound].jackpot3.winner = winner; uint teamComission = (rounds[currentRound].jackpot3.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot3.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot3.balance = 0; } } function payJackpot4() internal checkIsClosed() { address winner = getWinner(4); if (rounds[currentRound].jackpot4.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot4.balance); rounds[currentRound].jackpot4.winner = winner; uint teamComission = (rounds[currentRound].jackpot4.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot4.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot4.balance = 0; } } function payJackpot5() internal checkIsClosed() { address winner = getWinner(5); if (rounds[currentRound].jackpot5.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot5.balance); rounds[currentRound].jackpot5.winner = winner; uint teamComission = (rounds[currentRound].jackpot5.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot5.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot5.balance = 0; } } // // After time expiration, owner can call this function to activate the next round of the game // function activateNextRound(uint _startTime) public checkIsClosed() { payJackpot1(); payJackpot2(); payJackpot3(); payJackpot4(); payJackpot5(); currentRound++; rounds[currentRound] = Round(Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), 0, 0); rounds[currentRound].startTime = _startTime; rounds[currentRound].endTime = _startTime + 7 days; delete kingdoms; delete kingdomTransactions; } // GETTER AND SETTER FUNCTIONS function getKingdomCount() public view returns (uint kingdomCount) { return kingdoms.length; } function getJackpot(uint _nb) public view returns (address winner, uint balance) { if (_nb == 1) { return (getWinner(1), rounds[currentRound].jackpot1.balance); } else if (_nb == 2) { return (getWinner(2), rounds[currentRound].jackpot2.balance); } else if (_nb == 3) { return (getWinner(3), rounds[currentRound].jackpot3.balance); } else if (_nb == 4) { return (getWinner(4), rounds[currentRound].jackpot4.balance); } else if (_nb == 5) { return (getWinner(5), rounds[currentRound].jackpot5.balance); } } function getKingdomType(string _kingdomKey) public view returns (uint kingdomType) { return kingdoms[rounds[currentRound].kingdomsKeys[_kingdomKey]].kingdomType; } function getKingdomOwner(string _kingdomKey) public view returns (address owner) { return kingdoms[rounds[currentRound].kingdomsKeys[_kingdomKey]].owner; } function getKingdomInformations(string _kingdomKey) public view returns (string title, uint minimumPrice, uint lastTransaction, uint transactionCount, address currentOwner, uint kingdomType, bool locked) { uint kingdomId = rounds[currentRound].kingdomsKeys[_kingdomKey]; Kingdom storage kingdom = kingdoms[kingdomId]; return (kingdom.title, kingdom.minimumPrice, kingdom.lastTransaction, kingdom.transactionCount, kingdom.owner, kingdom.kingdomType, kingdom.locked); } // function upgradeTier(string _key) public { // // require(now < rounds[currentRound].endTime); // Round storage round = rounds[currentRound]; // uint kingdomId = round.kingdomsKeys[_key]; // Kingdom storage kingdom = kingdoms[kingdomId]; // uint wood = woodInterface.balanceOf(kingdom.owner); // require(wood >= 1); // kingdom.kingdomTier++; // } function getWinner(uint _type) public returns (address winner) { require(_type > 0); require(_type < 6); address addr; uint maxPoints = 0; Round storage round = rounds[currentRound]; for (uint index = 0; index < kingdoms.length; index++) { if (_type == kingdoms[index].kingdomType) { address userAddress = kingdoms[index].owner; if(kingdoms[index].kingdomTier == 1) { round.scores[msg.sender] = round.scores[msg.sender] + 1; } else if(kingdoms[index].kingdomTier == 2) { round.scores[msg.sender] = round.scores[msg.sender] + 3; } else if (kingdoms[index].kingdomTier == 3) { round.scores[msg.sender] = round.scores[msg.sender] + 5; } else if (kingdoms[index].kingdomTier == 4) { round.scores[msg.sender] = round.scores[msg.sender] + 8; } else if (kingdoms[index].kingdomTier == 5) { round.scores[msg.sender] = round.scores[msg.sender] + 13; } if(round.scores[msg.sender] == maxPoints) { if(lastTransaction[userAddress] < lastTransaction[winner]) { addr = userAddress; } } else if (round.scores[msg.sender] > maxPoints) { maxPoints = round.scores[msg.sender]; addr = userAddress; } } } return addr; } }
CONTRACT CONSTRUCTOR
function Map(address _bookerAddress, address _woodAddress, uint _startTime, uint _endTime) { bookerAddress = _bookerAddress; woodAddress = _woodAddress; woodInterface = ERC20Basic(_woodAddress); currentRound = 1; rounds[currentRound] = Round(Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), 0, 0); rounds[currentRound].jackpot1 = Jackpot(address(0), 0); rounds[currentRound].jackpot2 = Jackpot(address(0), 0); rounds[currentRound].jackpot3 = Jackpot(address(0), 0); rounds[currentRound].jackpot4 = Jackpot(address(0), 0); rounds[currentRound].jackpot5 = Jackpot(address(0), 0); rounds[currentRound].startTime = _startTime; rounds[currentRound].endTime = _endTime; }
10,692,855
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract BBW is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; // Sale uint256 public constant TOTAL_SUPPLY = 10000; uint256 public constant PUBLIC_SUPPLY = 9191; uint public constant MAX_PURCHASABLE = 100; uint public constant PRESALE_MAX_PURCHASABLE = 3; uint256 public constant MINT_PRICE = 100000000000000000; // 0.1 ETH // Dates uint256 public presaleStartTime = 1635591600; // Sat Oct 30 2021 11:00:00 GMT+0000 uint256 public presaleEndTime = 1635850800; // Tue Nov 02 2021 11:00:00 GMT+0000 uint256 public saleStartTime = 1635854400; // Tue Nov 02 2021 12:00:00 GMT+0000 // Team can emergency start/pause sale bool public saleStarted = true; // Base URI string private _baseURIextended = "ipfs://QmRC3ZuqFeBLkEobj3i8jLpXRRwxQZcpDzYEARJPR9D321/"; string private _contractURI = "ipfs://QmS8mnG2snYzMaahoAuLtMrECVQMMZff74T42bbC7fND93"; // Reveal variables bool public metadataRevealed = false; bool public locked = false; mapping(address => bool) public whitelistedAddresses; constructor() ERC721("BullsandBears Genesis", "BBW") { } function _baseURI() internal view virtual override returns (string memory) { return _baseURIextended; } function setBaseURI(string memory baseURI_) external onlyOwner() { require(!locked, "locked functions"); _baseURIextended = baseURI_; } function setContractURI(string memory newuri) public onlyOwner { require(!locked, "locked functions"); _contractURI = newuri; } function contractURI() public view returns (string memory) { return _contractURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { string memory baseURI = _baseURI(); if (!metadataRevealed) { return baseURI; } else { return string(abi.encodePacked(baseURI, tokenId.toString(), ".json")); } } function mint(uint256 amountToMint) public payable { require(saleStarted == true, "Sale is not active."); uint256 mintLimit = MAX_PURCHASABLE; uint256 time = block.timestamp; if (time < saleStartTime) { if (whitelistedAddresses[msg.sender]) { require(time >= presaleStartTime, "Presale has not started yet."); require(time <= presaleEndTime, "Presale has ended."); } else { revert("Sale has not started yet."); } mintLimit = PRESALE_MAX_PURCHASABLE; } require(totalSupply() < PUBLIC_SUPPLY, "All BullsandBears have been minted."); require(amountToMint > 0, "Minimum mint is 1 BullsandBears."); require(amountToMint <= mintLimit, string(abi.encodePacked("Maximum mint is ", mintLimit.toString(), " BullsandBears."))); require(balanceOf(msg.sender).add(amountToMint) <= mintLimit, string(abi.encodePacked("You have already minted ", mintLimit.toString(), " BullsandBears."))); require(totalSupply() + amountToMint <= PUBLIC_SUPPLY, "The amount of BullsandBears you are trying to mint exceeds the max supply."); require(MINT_PRICE.mul(amountToMint) == msg.value, "Incorrect Ether value."); _mint(amountToMint); } function _mint(uint256 amountToMint) private { for (uint256 i = 0; i < amountToMint; i++) { _safeMint(msg.sender, totalSupply() + 1); } } function ownerMint(uint256 amountToMint) public onlyOwner { require(totalSupply() < TOTAL_SUPPLY, "All BullsandBears have been minted."); require(totalSupply() + amountToMint <= TOTAL_SUPPLY, "The amount of BullsandBears you are trying to mint exceeds the max supply."); _mint(amountToMint); } function reveal() public onlyOwner { metadataRevealed = true; } function batchWhitelist(address[] memory _users) public onlyOwner { uint size = _users.length; for(uint256 i = 0; i < size; i++){ address user = _users[i]; whitelistedAddresses[user] = true; } } function startSale() public onlyOwner { saleStarted = true; } function pauseSale() public onlyOwner { saleStarted = false; } function setPresaleStartTime(uint256 time) public onlyOwner { require(time < saleStartTime, "Presale start time should be less than sale start time."); presaleStartTime = time; } function setPresaleEndTime(uint256 time) public onlyOwner { require(presaleStartTime < time, "Presale end time should be greater than presale time."); require(time < saleStartTime, "Presale end time should be less than sale start time."); presaleEndTime = time; } function setSaleStartTime(uint256 time) public onlyOwner { require(presaleStartTime < time, "Sale start time should be greater than presale start time."); saleStartTime = time; } // and for the eternity.... function lockMetadata() external onlyOwner { locked = true; } function withdraw() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../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; /** * @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 "../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; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
and for the eternity....
function lockMetadata() external onlyOwner { locked = true; }
182,867
./full_match/80001/0xd0f330338c533a0394d1533E47a8a4425E0Fd076/sources/contracts/Staking.sol
Header: Get an estimate for derivativeToken given for _amount of derivativeToken. [var] _amount: Amount of stakingToken. return: Equivalent derivativeToken note: Staked amount may be different from quoted amount due to changes in contract between calls./
function GetStakeQuote(uint _amount) external view returns(uint){ return _GetStakeQuote(_amount); }
9,496,548
./partial_match/1/0x8a1BbEf259B00cEd668A8c69e50D92619C672176/sources/contracts/AvatarToken.sol
Update the royalty fee
function updateRoyaltyPercent(uint96 royaltyPercent) public onlyOwner { _royaltyPercent = royaltyPercent; }
2,880,350
./partial_match/1/0x88888c037DF4527933fa8Ab203a89e1e6E58db70/sources/AdminUpgradeableProxy.sol
Returns an `StringSlot` representation of the string storage pointer `store`./ @solidity memory-safe-assembly
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { assembly { r.slot := store.slot } }
15,946,521
./full_match/3/0x3Dc329b324cDC77aC885740B524F82d066Ca0d0b/sources/stakingOliver/UBXTStaking.sol
update token per block value
function updateTokenPerBlock(uint256 _tokenPerBlock) public onlyOwner { massUpdatePools(); tokenPerBlock = _tokenPerBlock; }
8,239,112
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; // ============ Internal Imports ============ import {Home} from "../Home.sol"; import {Version0} from "../Version0.sol"; import {XAppConnectionManager, TypeCasts} from "../XAppConnectionManager.sol"; import {IMessageRecipient} from "../../interfaces/IMessageRecipient.sol"; import {GovernanceMessage} from "./GovernanceMessage.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; contract GovernanceRouter is Version0, Initializable, IMessageRecipient { // ============ Libraries ============ using SafeMath for uint256; using TypedMemView for bytes; using TypedMemView for bytes29; using GovernanceMessage for bytes29; // ============ Immutables ============ uint32 public immutable localDomain; // number of seconds before recovery can be activated uint256 public immutable recoveryTimelock; // ============ Public Storage ============ // timestamp when recovery timelock expires; 0 if timelock has not been initiated uint256 public recoveryActiveAt; // the address of the recovery manager multisig address public recoveryManager; // the local entity empowered to call governance functions, set to 0x0 on non-Governor chains address public governor; // domain of Governor chain -- for accepting incoming messages from Governor uint32 public governorDomain; // xAppConnectionManager contract which stores Replica addresses XAppConnectionManager public xAppConnectionManager; // domain -> remote GovernanceRouter contract address mapping(uint32 => bytes32) public routers; // array of all domains with registered GovernanceRouter uint32[] public domains; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[43] private __GAP; // ============ Events ============ /** * @notice Emitted a remote GovernanceRouter address is added, removed, or changed * @param domain the domain of the remote Router * @param previousRouter the previously registered router; 0 if router is being added * @param newRouter the new registered router; 0 if router is being removed */ event SetRouter( uint32 indexed domain, bytes32 previousRouter, bytes32 newRouter ); /** * @notice Emitted when the Governor role is transferred * @param previousGovernorDomain the domain of the previous Governor * @param newGovernorDomain the domain of the new Governor * @param previousGovernor the address of the previous Governor; 0 if the governor was remote * @param newGovernor the address of the new Governor; 0 if the governor is remote */ event TransferGovernor( uint32 previousGovernorDomain, uint32 newGovernorDomain, address indexed previousGovernor, address indexed newGovernor ); /** * @notice Emitted when the RecoveryManager role is transferred * @param previousRecoveryManager the address of the previous RecoveryManager * @param newRecoveryManager the address of the new RecoveryManager */ event TransferRecoveryManager( address indexed previousRecoveryManager, address indexed newRecoveryManager ); /** * @notice Emitted when recovery state is initiated by the RecoveryManager * @param recoveryManager the address of the current RecoveryManager who initiated the transition * @param recoveryActiveAt the block at which recovery state will be active */ event InitiateRecovery( address indexed recoveryManager, uint256 recoveryActiveAt ); /** * @notice Emitted when recovery state is exited by the RecoveryManager * @param recoveryManager the address of the current RecoveryManager who initiated the transition */ event ExitRecovery(address recoveryManager); modifier typeAssert(bytes29 _view, GovernanceMessage.Types _type) { _view.assertType(uint40(_type)); _; } // ============ Modifiers ============ modifier onlyReplica() { require(xAppConnectionManager.isReplica(msg.sender), "!replica"); _; } modifier onlyGovernorRouter(uint32 _domain, bytes32 _address) { require(_isGovernorRouter(_domain, _address), "!governorRouter"); _; } modifier onlyGovernor() { require(msg.sender == governor, "! called by governor"); _; } modifier onlyRecoveryManager() { require(msg.sender == recoveryManager, "! called by recovery manager"); _; } modifier onlyInRecovery() { require(inRecovery(), "! in recovery"); _; } modifier onlyNotInRecovery() { require(!inRecovery(), "in recovery"); _; } modifier onlyGovernorOrRecoveryManager() { if (!inRecovery()) { require(msg.sender == governor, "! called by governor"); } else { require( msg.sender == recoveryManager, "! called by recovery manager" ); } _; } // ============ Constructor ============ constructor(uint32 _localDomain, uint256 _recoveryTimelock) { localDomain = _localDomain; recoveryTimelock = _recoveryTimelock; } // ============ Initializer ============ function initialize( address _xAppConnectionManager, address _recoveryManager ) public initializer { // initialize governor address _governorAddr = msg.sender; bool _isLocalGovernor = true; _transferGovernor(localDomain, _governorAddr, _isLocalGovernor); // initialize recovery manager recoveryManager = _recoveryManager; // initialize XAppConnectionManager setXAppConnectionManager(_xAppConnectionManager); require( xAppConnectionManager.localDomain() == localDomain, "XAppConnectionManager bad domain" ); } // ============ External Functions ============ /** * @notice Handle Optics messages * For all non-Governor chains to handle messages * sent from the Governor chain via Optics. * Governor chain should never receive messages, * because non-Governor chains are not able to send them * @param _origin The domain (of the Governor Router) * @param _sender The message sender (must be the Governor Router) * @param _message The message */ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external override onlyReplica onlyGovernorRouter(_origin, _sender) { bytes29 _msg = _message.ref(0); if (_msg.isValidCall()) { _handleCall(_msg.tryAsCall()); } else if (_msg.isValidTransferGovernor()) { _handleTransferGovernor(_msg.tryAsTransferGovernor()); } else if (_msg.isValidSetRouter()) { _handleSetRouter(_msg.tryAsSetRouter()); } else { require(false, "!valid message type"); } } /** * @notice Dispatch calls locally * @param _calls The calls */ function callLocal(GovernanceMessage.Call[] calldata _calls) external onlyGovernorOrRecoveryManager { for (uint256 i = 0; i < _calls.length; i++) { _dispatchCall(_calls[i]); } } /** * @notice Dispatch calls on a remote chain via the remote GovernanceRouter * @param _destination The domain of the remote chain * @param _calls The calls */ function callRemote( uint32 _destination, GovernanceMessage.Call[] calldata _calls ) external onlyGovernor onlyNotInRecovery { // ensure that destination chain has enrolled router bytes32 _router = _mustHaveRouter(_destination); // format call message bytes memory _msg = GovernanceMessage.formatCalls(_calls); // dispatch call message using Optics Home(xAppConnectionManager.home()).dispatch( _destination, _router, _msg ); } /** * @notice Transfer governorship * @param _newDomain The domain of the new governor * @param _newGovernor The address of the new governor */ function transferGovernor(uint32 _newDomain, address _newGovernor) external onlyGovernor onlyNotInRecovery { bool _isLocalGovernor = _isLocalDomain(_newDomain); // transfer the governor locally _transferGovernor(_newDomain, _newGovernor, _isLocalGovernor); // if the governor domain is local, we only need to change the governor address locally // no need to message remote routers; they should already have the same domain set and governor = bytes32(0) if (_isLocalGovernor) { return; } // format transfer governor message bytes memory _transferGovernorMessage = GovernanceMessage .formatTransferGovernor( _newDomain, TypeCasts.addressToBytes32(_newGovernor) ); // send transfer governor message to all remote routers // note: this assumes that the Router is on the global GovernorDomain; // this causes a process error when relinquishing governorship // on a newly deployed domain which is not the GovernorDomain _sendToAllRemoteRouters(_transferGovernorMessage); } /** * @notice Transfer recovery manager role * @dev callable by the recoveryManager at any time to transfer the role * @param _newRecoveryManager The address of the new recovery manager */ function transferRecoveryManager(address _newRecoveryManager) external onlyRecoveryManager { emit TransferRecoveryManager(recoveryManager, _newRecoveryManager); recoveryManager = _newRecoveryManager; } /** * @notice Set the router address for a given domain and * dispatch the change to all remote routers * @param _domain The domain * @param _router The address of the new router */ function setRouter(uint32 _domain, bytes32 _router) external onlyGovernor onlyNotInRecovery { // set the router locally _setRouter(_domain, _router); // format message to set the router on all remote routers bytes memory _setRouterMessage = GovernanceMessage.formatSetRouter( _domain, _router ); _sendToAllRemoteRouters(_setRouterMessage); } /** * @notice Set the router address *locally only* * for the deployer to setup the router mapping locally * before transferring governorship to the "true" governor * @dev External helper for contract setup * @param _domain The domain * @param _router The new router */ function setRouterLocal(uint32 _domain, bytes32 _router) external onlyGovernorOrRecoveryManager { // set the router locally _setRouter(_domain, _router); } /** * @notice Set the address of the XAppConnectionManager * @dev Domain/address validation helper * @param _xAppConnectionManager The address of the new xAppConnectionManager */ function setXAppConnectionManager(address _xAppConnectionManager) public onlyGovernorOrRecoveryManager { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); } /** * @notice Initiate the recovery timelock * @dev callable by the recovery manager */ function initiateRecoveryTimelock() external onlyNotInRecovery onlyRecoveryManager { require(recoveryActiveAt == 0, "recovery already initiated"); // set the time that recovery will be active recoveryActiveAt = block.timestamp.add(recoveryTimelock); emit InitiateRecovery(recoveryManager, recoveryActiveAt); } /** * @notice Exit recovery mode * @dev callable by the recovery manager to end recovery mode */ function exitRecovery() external onlyRecoveryManager { require(recoveryActiveAt != 0, "recovery not initiated"); delete recoveryActiveAt; emit ExitRecovery(recoveryManager); } // ============ Public Functions ============ /** * @notice Check if the contract is in recovery mode currently * @return TRUE iff the contract is actively in recovery mode currently */ function inRecovery() public view returns (bool) { uint256 _recoveryActiveAt = recoveryActiveAt; bool _recoveryInitiated = _recoveryActiveAt != 0; bool _recoveryActive = _recoveryActiveAt <= block.timestamp; return _recoveryInitiated && _recoveryActive; } // ============ Internal Functions ============ /** * @notice Handle message dispatching calls locally * @param _msg The message */ function _handleCall(bytes29 _msg) internal typeAssert(_msg, GovernanceMessage.Types.Call) { GovernanceMessage.Call[] memory _calls = _msg.getCalls(); for (uint256 i = 0; i < _calls.length; i++) { _dispatchCall(_calls[i]); } } /** * @notice Handle message transferring governorship to a new Governor * @param _msg The message */ function _handleTransferGovernor(bytes29 _msg) internal typeAssert(_msg, GovernanceMessage.Types.TransferGovernor) { uint32 _newDomain = _msg.domain(); address _newGovernor = TypeCasts.bytes32ToAddress(_msg.governor()); bool _isLocalGovernor = _isLocalDomain(_newDomain); _transferGovernor(_newDomain, _newGovernor, _isLocalGovernor); } /** * @notice Handle message setting the router address for a given domain * @param _msg The message */ function _handleSetRouter(bytes29 _msg) internal typeAssert(_msg, GovernanceMessage.Types.SetRouter) { uint32 _domain = _msg.domain(); bytes32 _router = _msg.router(); _setRouter(_domain, _router); } /** * @notice Dispatch message to all remote routers * @param _msg The message */ function _sendToAllRemoteRouters(bytes memory _msg) internal { Home _home = Home(xAppConnectionManager.home()); for (uint256 i = 0; i < domains.length; i++) { if (domains[i] != uint32(0)) { _home.dispatch(domains[i], routers[domains[i]], _msg); } } } /** * @notice Dispatch call locally * @param _call The call * @return _ret */ function _dispatchCall(GovernanceMessage.Call memory _call) internal returns (bytes memory _ret) { address _toContract = TypeCasts.bytes32ToAddress(_call.to); // attempt to dispatch using low-level call bool _success; (_success, _ret) = _toContract.call(_call.data); // revert if the call failed require(_success, "call failed"); } /** * @notice Transfer governorship within this contract's state * @param _newDomain The domain of the new governor * @param _newGovernor The address of the new governor * @param _isLocalGovernor True if the newDomain is the localDomain */ function _transferGovernor( uint32 _newDomain, address _newGovernor, bool _isLocalGovernor ) internal { // require that the governor domain has a valid router if (!_isLocalGovernor) { _mustHaveRouter(_newDomain); } // Governor is 0x0 unless the governor is local address _newGov = _isLocalGovernor ? _newGovernor : address(0); // emit event before updating state variables emit TransferGovernor(governorDomain, _newDomain, governor, _newGov); // update state governorDomain = _newDomain; governor = _newGov; } /** * @notice Set the router for a given domain * @param _domain The domain * @param _newRouter The new router */ function _setRouter(uint32 _domain, bytes32 _newRouter) internal { bytes32 _previousRouter = routers[_domain]; // emit event at beginning in case return after remove emit SetRouter(_domain, _previousRouter, _newRouter); // if the router is being removed, remove the domain if (_newRouter == bytes32(0)) { _removeDomain(_domain); return; } // if the router is being added, add the domain if (_previousRouter == bytes32(0)) { _addDomain(_domain); } // update state with new router routers[_domain] = _newRouter; } /** * @notice Add a domain that has a router * @param _domain The domain */ function _addDomain(uint32 _domain) internal { domains.push(_domain); } /** * @notice Remove a domain and its associated router * @param _domain The domain */ function _removeDomain(uint32 _domain) internal { delete routers[_domain]; // find the index of the domain to remove & delete it from domains[] for (uint256 i = 0; i < domains.length; i++) { if (domains[i] == _domain) { delete domains[i]; return; } } } /** * @notice Determine if a given domain and address is the Governor Router * @param _domain The domain * @param _address The address of the domain's router * @return _ret True if the given domain/address is the * Governor Router. */ function _isGovernorRouter(uint32 _domain, bytes32 _address) internal view returns (bool) { return _domain == governorDomain && _address == routers[_domain]; } /** * @notice Determine if a given domain is the local domain * @param _domain The domain * @return _ret - True if the given domain is the local domain */ function _isLocalDomain(uint32 _domain) internal view returns (bool) { return _domain == localDomain; } /** * @notice Require that a domain has a router and returns the router * @param _domain The domain * @return _router - The domain's router */ function _mustHaveRouter(uint32 _domain) internal view returns (bytes32 _router) { _router = routers[_domain]; require(_router != bytes32(0), "!router"); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {QueueLib} from "../libs/Queue.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {MerkleTreeManager} from "./Merkle.sol"; import {QueueManager} from "./Queue.sol"; import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol"; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Home * @author Celo Labs Inc. * @notice Accepts messages to be dispatched to remote chains, * constructs a Merkle tree of the messages, * and accepts signatures from a bonded Updater * which notarize the Merkle tree roots. * Accepts submissions of fraudulent signatures * by the Updater and slashes the Updater in this case. */ contract Home is Version0, QueueManager, MerkleTreeManager, Common, OwnableUpgradeable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; using MerkleLib for MerkleLib.Tree; // ============ Constants ============ // Maximum bytes per message = 2 KiB // (somewhat arbitrarily set to begin) uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10; // ============ Public Storage Variables ============ // domain => next available nonce for the domain mapping(uint32 => uint32) public nonces; // contract responsible for Updater bonding, slashing and rotation IUpdaterManager public updaterManager; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[48] private __GAP; // ============ Events ============ /** * @notice Emitted when a new message is dispatched via Optics * @param leafIndex Index of message's leaf in merkle tree * @param destinationAndNonce Destination and destination-specific * nonce combined in single field ((destination << 32) & nonce) * @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message * @param committedRoot the latest notarized root submitted in the last signed Update * @param message Raw bytes of message */ event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message ); /** * @notice Emitted when proof of an improper update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root of the improper update * @param newRoot New root of the improper update * @param signature Signature on `oldRoot` and `newRoot */ event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature); /** * @notice Emitted when the Updater is slashed * (should be paired with ImproperUpdater or DoubleUpdate event) * @param updater The address of the updater * @param reporter The address of the entity that reported the updater misbehavior */ event UpdaterSlashed(address indexed updater, address indexed reporter); /** * @notice Emitted when Updater is rotated by the UpdaterManager * @param updater The address of the new updater */ event NewUpdater(address updater); /** * @notice Emitted when the UpdaterManager contract is changed * @param updaterManager The address of the new updaterManager */ event NewUpdaterManager(address updaterManager); // ============ Constructor ============ constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks // ============ Initializer ============ function initialize(IUpdaterManager _updaterManager) public initializer { // initialize owner & queue __Ownable_init(); __QueueManager_initialize(); // set Updater Manager contract and initialize Updater _setUpdaterManager(_updaterManager); address _updater = updaterManager.updater(); __Common_initialize(_updater); emit NewUpdater(_updater); } // ============ Modifiers ============ /** * @notice Ensures that function is called by the UpdaterManager contract */ modifier onlyUpdaterManager() { require(msg.sender == address(updaterManager), "!updaterManager"); _; } // ============ External: Updater & UpdaterManager Configuration ============ /** * @notice Set a new Updater * @param _updater the new Updater */ function setUpdater(address _updater) external onlyUpdaterManager { _setUpdater(_updater); } /** * @notice Set a new UpdaterManager contract * @dev Home(s) will initially be initialized using a trusted UpdaterManager contract; * we will progressively decentralize by swapping the trusted contract with a new implementation * that implements Updater bonding & slashing, and rules for Updater selection & rotation * @param _updaterManager the new UpdaterManager contract */ function setUpdaterManager(address _updaterManager) external onlyOwner { _setUpdaterManager(IUpdaterManager(_updaterManager)); } // ============ External Functions ============ /** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */ function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); } /** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */ function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); } /** * @notice Suggest an update for the Updater to sign and submit. * @dev If queue is empty, null bytes returned for both * (No update is necessary because no messages have been dispatched since the last update) * @return _committedRoot Latest root signed by the Updater * @return _new Latest enqueued Merkle root */ function suggestUpdate() external view returns (bytes32 _committedRoot, bytes32 _new) { if (queue.length() != 0) { _committedRoot = committedRoot; _new = queue.lastItem(); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(localDomain); } /** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */ function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; } // ============ Internal Functions ============ /** * @notice Set the UpdaterManager * @param _updaterManager Address of the UpdaterManager */ function _setUpdaterManager(IUpdaterManager _updaterManager) internal { require( Address.isContract(address(_updaterManager)), "!contract updaterManager" ); updaterManager = IUpdaterManager(_updaterManager); emit NewUpdaterManager(address(_updaterManager)); } /** * @notice Set the Updater * @param _updater Address of the Updater */ function _setUpdater(address _updater) internal { updater = _updater; emit NewUpdater(_updater); } /** * @notice Slash the Updater and set contract state to FAILED * @dev Called when fraud is proven (Improper Update or Double Update) */ function _fail() internal override { // set contract to FAILED _setFailed(); // slash Updater updaterManager.slashUpdater(msg.sender); emit UpdaterSlashed(updater, msg.sender); } /** * @notice Internal utility function that combines * `_destination` and `_nonce`. * @dev Both destination and nonce should be less than 2^32 - 1 * @param _destination Domain of destination chain * @param _nonce Current nonce for given destination chain * @return Returns (`_destination` << 32) & `_nonce` */ function _destinationAndNonce(uint32 _destination, uint32 _nonce) internal pure returns (uint64) { return (uint64(_destination) << 32) | _nonce; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title Version0 * @notice Version getter for contracts **/ contract Version0 { uint8 public constant VERSION = 0; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Home} from "./Home.sol"; import {Replica} from "./Replica.sol"; import {TypeCasts} from "../libs/TypeCasts.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title XAppConnectionManager * @author Celo Labs Inc. * @notice Manages a registry of local Replica contracts * for remote Home domains. Accepts Watcher signatures * to un-enroll Replicas attached to fraudulent remote Homes */ contract XAppConnectionManager is Ownable { // ============ Public Storage ============ // Home contract Home public home; // local Replica address => remote Home domain mapping(address => uint32) public replicaToDomain; // remote Home domain => local Replica address mapping(uint32 => address) public domainToReplica; // watcher address => replica remote domain => has/doesn't have permission mapping(address => mapping(uint32 => bool)) private watcherPermissions; // ============ Events ============ /** * @notice Emitted when a new Replica is enrolled / added * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaEnrolled(uint32 indexed domain, address replica); /** * @notice Emitted when a new Replica is un-enrolled / removed * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaUnenrolled(uint32 indexed domain, address replica); /** * @notice Emitted when Watcher permissions are changed * @param domain the remote domain of the Home contract for the Replica * @param watcher the address of the Watcher * @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed */ event WatcherPermissionSet( uint32 indexed domain, address watcher, bool access ); // ============ Modifiers ============ modifier onlyReplica() { require(isReplica(msg.sender), "!replica"); _; } // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor() Ownable() {} // ============ External Functions ============ /** * @notice Un-Enroll a replica contract * in the case that fraud was detected on the Home * @dev in the future, if fraud occurs on the Home contract, * the Watcher will submit their signature directly to the Home * and it can be relayed to all remote chains to un-enroll the Replicas * @param _domain the remote domain of the Home contract for the Replica * @param _updater the address of the Updater for the Home contract (also stored on Replica) * @param _signature signature of watcher on (domain, replica address, updater address) */ function unenrollReplica( uint32 _domain, bytes32 _updater, bytes memory _signature ) external { // ensure that the replica is currently set address _replica = domainToReplica[_domain]; require(_replica != address(0), "!replica exists"); // ensure that the signature is on the proper updater require( Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater), "!current updater" ); // get the watcher address from the signature // and ensure that the watcher has permission to un-enroll this replica address _watcher = _recoverWatcherFromSig( _domain, TypeCasts.addressToBytes32(_replica), _updater, _signature ); require(watcherPermissions[_watcher][_domain], "!valid watcher"); // remove the replica from mappings _unenrollReplica(_replica); } /** * @notice Set the address of the local Home contract * @param _home the address of the local Home contract */ function setHome(address _home) external onlyOwner { home = Home(_home); } /** * @notice Allow Owner to enroll Replica contract * @param _replica the address of the Replica * @param _domain the remote domain of the Home contract for the Replica */ function ownerEnrollReplica(address _replica, uint32 _domain) external onlyOwner { // un-enroll any existing replica _unenrollReplica(_replica); // add replica and domain to two-way mapping replicaToDomain[_replica] = _domain; domainToReplica[_domain] = _replica; emit ReplicaEnrolled(_domain, _replica); } /** * @notice Allow Owner to un-enroll Replica contract * @param _replica the address of the Replica */ function ownerUnenrollReplica(address _replica) external onlyOwner { _unenrollReplica(_replica); } /** * @notice Allow Owner to set Watcher permissions for a Replica * @param _watcher the address of the Watcher * @param _domain the remote domain of the Home contract for the Replica * @param _access TRUE to give the Watcher permissions, FALSE to remove permissions */ function setWatcherPermission( address _watcher, uint32 _domain, bool _access ) external onlyOwner { watcherPermissions[_watcher][_domain] = _access; emit WatcherPermissionSet(_domain, _watcher, _access); } /** * @notice Query local domain from Home * @return local domain */ function localDomain() external view returns (uint32) { return home.localDomain(); } /** * @notice Get access permissions for the watcher on the domain * @param _watcher the address of the watcher * @param _domain the domain to check for watcher permissions * @return TRUE iff _watcher has permission to un-enroll replicas on _domain */ function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) { return watcherPermissions[_watcher][_domain]; } // ============ Public Functions ============ /** * @notice Check whether _replica is enrolled * @param _replica the replica to check for enrollment * @return TRUE iff _replica is enrolled */ function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; } // ============ Internal Functions ============ /** * @notice Remove the replica from the two-way mappings * @param _replica replica to un-enroll */ function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); } /** * @notice Get the Watcher address from the provided signature * @return address of watcher that signed */ function _recoverWatcherFromSig( uint32 _domain, bytes32 _replica, bytes32 _updater, bytes memory _signature ) internal view returns (address) { bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica)) .homeDomainHash(); bytes32 _digest = keccak256( abi.encodePacked(_homeDomainHash, _domain, _updater) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return ECDSA.recover(_digest, _signature); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IMessageRecipient { function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library GovernanceMessage { using TypedMemView for bytes; using TypedMemView for bytes29; uint256 private constant CALL_PREFIX_LEN = 64; uint256 private constant MSG_PREFIX_NUM_ITEMS = 2; uint256 private constant MSG_PREFIX_LEN = 2; uint256 private constant GOV_ACTION_LEN = 37; enum Types { Invalid, // 0 Call, // 1 TransferGovernor, // 2 SetRouter, // 3 Data // 4 } struct Call { bytes32 to; bytes data; } modifier typeAssert(bytes29 _view, Types _t) { _view.assertType(uint40(_t)); _; } // Types.Call function data(bytes29 _view) internal view returns (bytes memory _data) { _data = TypedMemView.clone( _view.slice(CALL_PREFIX_LEN, dataLen(_view), uint40(Types.Data)) ); } function formatCalls(Call[] memory _calls) internal view returns (bytes memory _msg) { uint256 _numCalls = _calls.length; bytes29[] memory _encodedCalls = new bytes29[]( _numCalls + MSG_PREFIX_NUM_ITEMS ); // Add Types.Call identifier _encodedCalls[0] = abi.encodePacked(Types.Call).ref(0); // Add number of calls _encodedCalls[1] = abi.encodePacked(uint8(_numCalls)).ref(0); for (uint256 i = 0; i < _numCalls; i++) { Call memory _call = _calls[i]; bytes29 _callMsg = abi .encodePacked(_call.to, _call.data.length, _call.data) .ref(0); _encodedCalls[i + MSG_PREFIX_NUM_ITEMS] = _callMsg; } _msg = TypedMemView.join(_encodedCalls); } function formatTransferGovernor(uint32 _domain, bytes32 _governor) internal view returns (bytes memory _msg) { _msg = TypedMemView.clone( mustBeTransferGovernor( abi .encodePacked(Types.TransferGovernor, _domain, _governor) .ref(0) ) ); } function formatSetRouter(uint32 _domain, bytes32 _router) internal view returns (bytes memory _msg) { _msg = TypedMemView.clone( mustBeSetRouter( abi.encodePacked(Types.SetRouter, _domain, _router).ref(0) ) ); } function getCalls(bytes29 _msg) internal view returns (Call[] memory) { uint8 _numCalls = uint8(_msg.indexUint(1, 1)); // Skip message prefix bytes29 _msgPtr = _msg.slice( MSG_PREFIX_LEN, _msg.len() - MSG_PREFIX_LEN, uint40(Types.Call) ); Call[] memory _calls = new Call[](_numCalls); uint256 counter = 0; while (_msgPtr.len() > 0) { _calls[counter].to = to(_msgPtr); _calls[counter].data = data(_msgPtr); _msgPtr = nextCall(_msgPtr); counter++; } return _calls; } function nextCall(bytes29 _view) internal pure typeAssert(_view, Types.Call) returns (bytes29) { uint256 lastCallLen = CALL_PREFIX_LEN + dataLen(_view); return _view.slice( lastCallLen, _view.len() - lastCallLen, uint40(Types.Call) ); } function messageType(bytes29 _view) internal pure returns (Types) { return Types(uint8(_view.typeOf())); } /* Message fields */ // All Types function identifier(bytes29 _view) internal pure returns (uint8) { return uint8(_view.indexUint(0, 1)); } // Types.Call function to(bytes29 _view) internal pure returns (bytes32) { return _view.index(0, 32); } // Types.Call function dataLen(bytes29 _view) internal pure returns (uint256) { return uint256(_view.index(32, 32)); } // Types.TransferGovernor & Types.EnrollRemote function domain(bytes29 _view) internal pure returns (uint32) { return uint32(_view.indexUint(1, 4)); } // Types.EnrollRemote function router(bytes29 _view) internal pure returns (bytes32) { return _view.index(5, 32); } // Types.TransferGovernor function governor(bytes29 _view) internal pure returns (bytes32) { return _view.index(5, 32); } /* Message Type: CALL struct Call { identifier, // message ID -- 1 byte numCalls, // number of calls -- 1 byte calls[], { to, // address to call -- 32 bytes dataLen, // call data length -- 32 bytes, data // call data -- 0+ bytes (length unknown) } } */ function isValidCall(bytes29 _view) internal pure returns (bool) { return identifier(_view) == uint8(Types.Call) && _view.len() >= CALL_PREFIX_LEN; } function isCall(bytes29 _view) internal pure returns (bool) { return isValidCall(_view) && messageType(_view) == Types.Call; } function tryAsCall(bytes29 _view) internal pure returns (bytes29) { if (isValidCall(_view)) { return _view.castTo(uint40(Types.Call)); } return TypedMemView.nullView(); } function mustBeCalls(bytes29 _view) internal pure returns (bytes29) { return tryAsCall(_view).assertValid(); } /* Message Type: TRANSFER GOVERNOR struct TransferGovernor { identifier, // message ID -- 1 byte domain, // domain of new governor -- 4 bytes addr // address of new governor -- 32 bytes } */ function isValidTransferGovernor(bytes29 _view) internal pure returns (bool) { return identifier(_view) == uint8(Types.TransferGovernor) && _view.len() == GOV_ACTION_LEN; } function isTransferGovernor(bytes29 _view) internal pure returns (bool) { return isValidTransferGovernor(_view) && messageType(_view) == Types.TransferGovernor; } function tryAsTransferGovernor(bytes29 _view) internal pure returns (bytes29) { if (isValidTransferGovernor(_view)) { return _view.castTo(uint40(Types.TransferGovernor)); } return TypedMemView.nullView(); } function mustBeTransferGovernor(bytes29 _view) internal pure returns (bytes29) { return tryAsTransferGovernor(_view).assertValid(); } /* Message Type: ENROLL ROUTER struct SetRouter { identifier, // message ID -- 1 byte domain, // domain of new router -- 4 bytes addr // address of new router -- 32 bytes } */ function isValidSetRouter(bytes29 _view) internal pure returns (bool) { return identifier(_view) == uint8(Types.SetRouter) && _view.len() == GOV_ACTION_LEN; } function isSetRouter(bytes29 _view) internal pure returns (bool) { return isValidSetRouter(_view) && messageType(_view) == Types.SetRouter; } function tryAsSetRouter(bytes29 _view) internal pure returns (bytes29) { if (isValidSetRouter(_view)) { return _view.castTo(uint40(Types.SetRouter)); } return TypedMemView.nullView(); } function mustBeSetRouter(bytes29 _view) internal pure returns (bytes29) { return tryAsSetRouter(_view).assertValid(); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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)); } } // 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 OR Apache-2.0 pragma solidity >=0.5.10; import {SafeMath} from "./SafeMath.sol"; library TypedMemView { using SafeMath for uint256; // Why does this exist? // the solidity `bytes memory` type has a few weaknesses. // 1. You can't index ranges effectively // 2. You can't slice without copying // 3. The underlying data may represent any type // 4. Solidity never deallocates memory, and memory costs grow // superlinearly // By using a memory view instead of a `bytes memory` we get the following // advantages: // 1. Slices are done on the stack, by manipulating the pointer // 2. We can index arbitrary ranges and quickly convert them to stack types // 3. We can insert type info into the pointer, and typecheck at runtime // This makes `TypedMemView` a useful tool for efficient zero-copy // algorithms. // Why bytes29? // We want to avoid confusion between views, digests, and other common // types so we chose a large and uncommonly used odd number of bytes // // Note that while bytes are left-aligned in a word, integers and addresses // are right-aligned. This means when working in assembly we have to // account for the 3 unused bytes on the righthand side // // First 5 bytes are a type flag. // - ff_ffff_fffe is reserved for unknown type. // - ff_ffff_ffff is reserved for invalid types/errors. // next 12 are memory address // next 12 are len // bottom 3 bytes are empty // Assumptions: // - non-modification of memory. // - No Solidity updates // - - wrt free mem point // - - wrt bytes representation in memory // - - wrt memory addressing in general // Usage: // - create type constants // - use `assertType` for runtime type assertions // - - unfortunately we can't do this at compile time yet :( // - recommended: implement modifiers that perform type checking // - - e.g. // - - `uint40 constant MY_TYPE = 3;` // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }` // - instantiate a typed view from a bytearray using `ref` // - use `index` to inspect the contents of the view // - use `slice` to create smaller views into the same memory // - - `slice` can increase the offset // - - `slice can decrease the length` // - - must specify the output type of `slice` // - - `slice` will return a null view if you try to overrun // - - make sure to explicitly check for this with `notNull` or `assertType` // - use `equal` for typed comparisons. // The null view bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff; uint8 constant TWELVE_BYTES = 96; /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _b The byte * @return char - The encoded hex character */ function nibbleHex(uint8 _b) internal pure returns (uint8 char) { // This can probably be done more efficiently, but it's only in error // paths, so we don't really care :) uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4 if (_nibble == 0xf0) {return 0x30;} // 0 if (_nibble == 0xf1) {return 0x31;} // 1 if (_nibble == 0xf2) {return 0x32;} // 2 if (_nibble == 0xf3) {return 0x33;} // 3 if (_nibble == 0xf4) {return 0x34;} // 4 if (_nibble == 0xf5) {return 0x35;} // 5 if (_nibble == 0xf6) {return 0x36;} // 6 if (_nibble == 0xf7) {return 0x37;} // 7 if (_nibble == 0xf8) {return 0x38;} // 8 if (_nibble == 0xf9) {return 0x39;} // 9 if (_nibble == 0xfa) {return 0x61;} // a if (_nibble == 0xfb) {return 0x62;} // b if (_nibble == 0xfc) {return 0x63;} // c if (_nibble == 0xfd) {return 0x64;} // d if (_nibble == 0xfe) {return 0x65;} // e if (_nibble == 0xff) {return 0x66;} // f } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _b The byte * @return encoded - The hex-encoded byte */ function byteHex(uint8 _b) internal pure returns (uint16 encoded) { encoded |= nibbleHex(_b >> 4); // top 4 bits encoded <<= 8; encoded |= nibbleHex(_b); // lower 4 bits } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * * @param _b The 32 bytes as uint256 * @return first - The top 16 bytes * @return second - The bottom 16 bytes */ function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); first |= byteHex(_byte); if (i != 16) { first <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255 ; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); second |= byteHex(_byte); if (i != 0) { second <<= 16; } } } /** * @notice Changes the endianness of a uint256. * @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel * @param _b The unsigned integer to reverse * @return v - The reversed value */ function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /** * @notice Create a mask with the highest `_len` bits set. * @param _len The length * @return mask - The mask */ function leftMask(uint8 _len) private pure returns (uint256 mask) { // ugly. redo without assembly? assembly { // solium-disable-previous-line security/no-inline-assembly mask := sar( sub(_len, 1), 0x8000000000000000000000000000000000000000000000000000000000000000 ) } } /** * @notice Return the null view. * @return bytes29 - The null view */ function nullView() internal pure returns (bytes29) { return NULL; } /** * @notice Check if the view is null. * @return bool - True if the view is null */ function isNull(bytes29 memView) internal pure returns (bool) { return memView == NULL; } /** * @notice Check if the view is not null. * @return bool - True if the view is not null */ function notNull(bytes29 memView) internal pure returns (bool) { return !isNull(memView); } /** * @notice Check if the view is of a valid type and points to a valid location * in memory. * @dev We perform this check by examining solidity's unallocated memory * pointer and ensuring that the view's upper bound is less than that. * @param memView The view * @return ret - True if the view is valid */ function isValid(bytes29 memView) internal pure returns (bool ret) { if (typeOf(memView) == 0xffffffffff) {return false;} uint256 _end = end(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ret := not(gt(_end, mload(0x40))) } } /** * @notice Require that a typed memory view be valid. * @dev Returns the view for easy chaining. * @param memView The view * @return bytes29 - The validated view */ function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; } /** * @notice Return true if the memview is of the expected type. Otherwise false. * @param memView The view * @param _expected The expected type * @return bool - True if the memview is of the expected type */ function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) { return typeOf(memView) == _expected; } /** * @notice Require that a typed memory view has a specific type. * @dev Returns the view for easy chaining. * @param memView The view * @param _expected The expected type * @return bytes29 - The view with validated type */ function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) { if (!isType(memView, _expected)) { (, uint256 g) = encodeHex(uint256(typeOf(memView))); (, uint256 e) = encodeHex(uint256(_expected)); string memory err = string( abi.encodePacked( "Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e) ) ); revert(err); } return memView; } /** * @notice Return an identical view with a different type. * @param memView The view * @param _newType The new type * @return newView - The new view with the specified type */ function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } } /** * @notice Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) { assembly { // solium-disable-previous-line security/no-inline-assembly newView := shl(96, or(newView, _type)) // insert type newView := shl(96, or(newView, _loc)) // insert loc newView := shl(24, or(newView, _len)) // empty bottom 3 bytes } } /** * @notice Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) { uint256 _end = _loc.add(_len); assembly { // solium-disable-previous-line security/no-inline-assembly if gt(_end, mload(0x40)) { _end := 0 } } if (_end == 0) { return NULL; } newView = unsafeBuildUnchecked(_type, _loc, _len); } /** * @notice Instantiate a memory view from a byte array. * @dev Note that due to Solidity memory representation, it is not possible to * implement a deref, as the `bytes` type stores its len in memory. * @param arr The byte array * @param newType The type * @return bytes29 - The memory view */ function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) { uint256 _len = arr.length; uint256 _loc; assembly { // solium-disable-previous-line security/no-inline-assembly _loc := add(arr, 0x20) // our view is of the data, not the struct } return build(newType, _loc, _len); } /** * @notice Return the associated type information. * @param memView The memory view * @return _type - The type associated with the view */ function typeOf(bytes29 memView) internal pure returns (uint40 _type) { assembly { // solium-disable-previous-line security/no-inline-assembly // 216 == 256 - 40 _type := shr(216, memView) // shift out lower 24 bytes } } /** * @notice Optimized type comparison. Checks that the 5-byte type flag is equal. * @param left The first view * @param right The second view * @return bool - True if the 5-byte type flag is equal */ function sameType(bytes29 left, bytes29 right) internal pure returns (bool) { return (left ^ right) >> (2 * TWELVE_BYTES) == 0; } /** * @notice Return the memory address of the underlying bytes. * @param memView The view * @return _loc - The memory address */ function loc(bytes29 memView) internal pure returns (uint96 _loc) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly // 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space) _loc := and(shr(120, memView), _mask) } } /** * @notice The number of memory words this memory view occupies, rounded up. * @param memView The view * @return uint256 - The number of memory words */ function words(bytes29 memView) internal pure returns (uint256) { return uint256(len(memView)).add(32) / 32; } /** * @notice The in-memory footprint of a fresh copy of the view. * @param memView The view * @return uint256 - The in-memory footprint of a fresh copy of the view. */ function footprint(bytes29 memView) internal pure returns (uint256) { return words(memView) * 32; } /** * @notice The number of bytes of the view. * @param memView The view * @return _len - The length of the view */ function len(bytes29 memView) internal pure returns (uint96 _len) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly _len := and(shr(24, memView), _mask) } } /** * @notice Returns the endpoint of `memView`. * @param memView The view * @return uint256 - The endpoint of `memView` */ function end(bytes29 memView) internal pure returns (uint256) { return loc(memView) + len(memView); } /** * @notice Safe slicing without memory modification. * @param memView The view * @param _index The start index * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) { uint256 _loc = loc(memView); // Ensure it doesn't overrun the view if (_loc.add(_index).add(_len) > end(memView)) { return NULL; } _loc = _loc.add(_index); return build(newType, _loc, _len); } /** * @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, 0, _len, newType); } /** * @notice Shortcut to `slice`. Gets a view representing the last `_len` byte. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, uint256(len(memView)).sub(_len), _len, newType); } /** * @notice Construct an error message for an indexing overrun. * @param _loc The memory address * @param _len The length * @param _index The index * @param _slice The slice where the overrun occurred * @return err - The err */ function indexErrOverrun( uint256 _loc, uint256 _len, uint256 _index, uint256 _slice ) internal pure returns (string memory err) { (, uint256 a) = encodeHex(_loc); (, uint256 b) = encodeHex(_len); (, uint256 c) = encodeHex(_index); (, uint256 d) = encodeHex(_slice); err = string( abi.encodePacked( "TypedMemView/index - Overran the view. Slice is at 0x", uint48(a), " with length 0x", uint48(b), ". Attempted to index at offset 0x", uint48(c), " with length 0x", uint48(d), "." ) ); } /** * @notice Load up to 32 bytes from the view onto the stack. * @dev Returns a bytes32 with only the `_bytes` highest bytes set. * This can be immediately cast to a smaller fixed-length byte array. * To automatically cast to an integer, use `indexUint`. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The 32 byte result */ function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) { if (_bytes == 0) {return bytes32(0);} if (_index.add(_bytes) > len(memView)) { revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes))); } require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes"); uint8 bitLength = _bytes * 8; uint256 _loc = loc(memView); uint256 _mask = leftMask(bitLength); assembly { // solium-disable-previous-line security/no-inline-assembly result := and(mload(add(_loc, _index)), _mask) } } /** * @notice Parse an unsigned integer from the view at `_index`. * @dev Requires that the view have >= `_bytes` bytes following that index. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8); } /** * @notice Parse an unsigned integer from LE bytes. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return reverseUint256(uint256(index(memView, _index, _bytes))); } /** * @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes * following that index. * @param memView The view * @param _index The index * @return address - The address */ function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) { return address(uint160(indexUint(memView, _index, 20))); } /** * @notice Return the keccak256 hash of the underlying memory * @param memView The view * @return digest - The keccak256 hash of the underlying memory */ function keccak(bytes29 memView) internal pure returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly digest := keccak256(_loc, _len) } } /** * @notice Return the sha2 digest of the underlying memory. * @dev We explicitly deallocate memory afterwards. * @param memView The view * @return digest - The sha2 hash of the underlying memory */ function sha2(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 digest := mload(ptr) } } /** * @notice Implements bitcoin's hash160 (rmd160(sha2())) * @param memView The pre-image * @return digest - the Digest */ function hash160(bytes29 memView) internal view returns (bytes20 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160 digest := mload(add(ptr, 0xc)) // return value is 0-prefixed. } } /** * @notice Implements bitcoin's hash256 (double sha2) * @param memView A view of the preimage * @return digest - the Digest */ function hash256(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2 digest := mload(ptr) } } /** * @notice Return true if the underlying memory is equal. Else false. * @param left The first view * @param right The second view * @return bool - True if the underlying memory is equal */ function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right); } /** * @notice Return false if the underlying memory is equal. Else true. * @param left The first view * @param right The second view * @return bool - False if the underlying memory is equal */ function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !untypedEqual(left, right); } /** * @notice Compares type equality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are the same */ function equal(bytes29 left, bytes29 right) internal pure returns (bool) { return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right)); } /** * @notice Compares type inequality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are not the same */ function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !equal(left, right); } /** * @notice Copy the view to a location, return an unsafe memory reference * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memView The view * @param _newLoc The new location * @return written - the unsafe memory reference */ function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) { require(notNull(memView), "TypedMemView/copyTo - Null pointer deref"); require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref"); uint256 _len = len(memView); uint256 _oldLoc = loc(memView); uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message } // use the identity precompile to copy // guaranteed not to fail, so pop the success pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len)) } written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len); } /** * @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to * the new memory * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param memView The view * @return ret - The view pointing to the new memory */ function clone(bytes29 memView) internal view returns (bytes memory ret) { uint256 ptr; uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer ret := ptr } unsafeCopyTo(memView, ptr + 0x20); assembly { // solium-disable-previous-line security/no-inline-assembly mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer mstore(ptr, _len) // write len of new array (in bytes) } } /** * @notice Join the views in memory, return an unsafe reference to the memory. * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memViews The views * @return unsafeView - The conjoined view pointing to the new memory */ function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) { assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _location) { revert(0x60, 0x20) // empty revert message } } uint256 _offset = 0; for (uint256 i = 0; i < memViews.length; i ++) { bytes29 memView = memViews[i]; unsafeCopyTo(memView, _location + _offset); _offset += len(memView); } unsafeView = unsafeBuildUnchecked(0, _location, _offset); } /** * @notice Produce the keccak256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The keccak256 digest */ function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return keccak(unsafeJoin(memViews, ptr)); } /** * @notice Produce the sha256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The sha256 digest */ function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return sha2(unsafeJoin(memViews, ptr)); } /** * @notice copies all views, joins them into a new bytearray. * @param memViews The views * @return ret - The new byte array */ function join(bytes29[] memory memViews) internal view returns (bytes memory ret) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } bytes29 _newView = unsafeJoin(memViews, ptr + 0x20); uint256 _written = len(_newView); uint256 _footprint = footprint(_newView); assembly { // solium-disable-previous-line security/no-inline-assembly // store the legnth mstore(ptr, _written) // new pointer is old + 0x20 + the footprint of the body mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr } } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Message} from "../libs/Message.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title Common * @author Celo Labs Inc. * @notice Shared utilities between Home and Replica. */ abstract contract Common is Initializable { // ============ Enums ============ // States: // 0 - UnInitialized - before initialize function is called // note: the contract is initialized at deploy time, so it should never be in this state // 1 - Active - as long as the contract has not become fraudulent // 2 - Failed - after a valid fraud proof has been submitted; // contract will no longer accept updates or new messages enum States { UnInitialized, Active, Failed } // ============ Immutable Variables ============ // Domain of chain on which the contract is deployed uint32 public immutable localDomain; // ============ Public Variables ============ // Address of bonded Updater address public updater; // Current state of contract States public state; // The latest root that has been signed by the Updater bytes32 public committedRoot; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[47] private __GAP; // ============ Events ============ /** * @notice Emitted when update is made on Home * or unconfirmed update root is submitted on Replica * @param homeDomain Domain of home contract * @param oldRoot Old merkle root * @param newRoot New merkle root * @param signature Updater's signature on `oldRoot` and `newRoot` */ event Update( uint32 indexed homeDomain, bytes32 indexed oldRoot, bytes32 indexed newRoot, bytes signature ); /** * @notice Emitted when proof of a double update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root shared between two conflicting updates * @param newRoot Array containing two conflicting new roots * @param signature Signature on `oldRoot` and `newRoot`[0] * @param signature2 Signature on `oldRoot` and `newRoot`[1] */ event DoubleUpdate( bytes32 oldRoot, bytes32[2] newRoot, bytes signature, bytes signature2 ); // ============ Modifiers ============ /** * @notice Ensures that contract state != FAILED when the function is called */ modifier notFailed() { require(state != States.Failed, "failed state"); _; } // ============ Constructor ============ constructor(uint32 _localDomain) { localDomain = _localDomain; } // ============ Initializer ============ function __Common_initialize(address _updater) internal initializer { updater = _updater; state = States.Active; } // ============ External Functions ============ /** * @notice Called by external agent. Checks that signatures on two sets of * roots are valid and that the new roots conflict with each other. If both * cases hold true, the contract is failed and a `DoubleUpdate` event is * emitted. * @dev When `fail()` is called on Home, updater is slashed. * @param _oldRoot Old root shared between two conflicting updates * @param _newRoot Array containing two conflicting new roots * @param _signature Signature on `_oldRoot` and `_newRoot`[0] * @param _signature2 Signature on `_oldRoot` and `_newRoot`[1] */ function doubleUpdate( bytes32 _oldRoot, bytes32[2] calldata _newRoot, bytes calldata _signature, bytes calldata _signature2 ) external notFailed { if ( Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) && Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) && _newRoot[0] != _newRoot[1] ) { _fail(); emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view virtual returns (bytes32); // ============ Internal Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" * @param _homeDomain the Home domain to hash */ function _homeDomainHash(uint32 _homeDomain) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_homeDomain, "OPTICS")); } /** * @notice Set contract state to FAILED * @dev Called when a valid fraud proof is submitted */ function _setFailed() internal { state = States.Failed; } /** * @notice Moves the contract into failed state * @dev Called when fraud is proven * (Double Update is submitted on Home or Replica, * or Improper Update is submitted on Home) */ function _fail() internal virtual; /** * @notice Checks that signature was signed by Updater * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Signature on `_oldRoot` and `_newRoot` * @return TRUE iff signature is valid signed by updater **/ function _isUpdaterSignature( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) internal view returns (bool) { bytes32 _digest = keccak256( abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return (ECDSA.recover(_digest, _signature) == updater); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title QueueLib * @author Celo Labs Inc. * @notice Library containing queue struct and operations for queue used by * Home and Replica. **/ library QueueLib { /** * @notice Queue struct * @dev Internally keeps track of the `first` and `last` elements through * indices and a mapping of indices to enqueued elements. **/ struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; } /** * @notice Initializes the queue * @dev Empty state denoted by _q.first > q._last. Queue initialized * with _q.first = 1 and _q.last = 0. **/ function initialize(Queue storage _q) internal { if (_q.first == 0) { _q.first = 1; } } /** * @notice Enqueues a single new element * @param _item New element to be enqueued * @return _last Index of newly enqueued element **/ function enqueue(Queue storage _q, bytes32 _item) internal returns (uint128 _last) { _last = _q.last + 1; _q.last = _last; if (_item != bytes32(0)) { // saves gas if we're queueing 0 _q.queue[_last] = _item; } } /** * @notice Dequeues element at front of queue * @dev Removes dequeued element from storage * @return _item Dequeued element **/ function dequeue(Queue storage _q) internal returns (bytes32 _item) { uint128 _last = _q.last; uint128 _first = _q.first; require(_length(_last, _first) != 0, "Empty"); _item = _q.queue[_first]; if (_item != bytes32(0)) { // saves gas if we're dequeuing 0 delete _q.queue[_first]; } _q.first = _first + 1; } /** * @notice Batch enqueues several elements * @param _items Array of elements to be enqueued * @return _last Index of last enqueued element **/ function enqueue(Queue storage _q, bytes32[] memory _items) internal returns (uint128 _last) { _last = _q.last; for (uint256 i = 0; i < _items.length; i += 1) { _last += 1; bytes32 _item = _items[i]; if (_item != bytes32(0)) { _q.queue[_last] = _item; } } _q.last = _last; } /** * @notice Batch dequeues `_number` elements * @dev Reverts if `_number` > queue length * @param _number Number of elements to dequeue * @return Array of dequeued elements **/ function dequeue(Queue storage _q, uint256 _number) internal returns (bytes32[] memory) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted require(_length(_last, _first) >= _number, "Insufficient"); bytes32[] memory _items = new bytes32[](_number); for (uint256 i = 0; i < _number; i++) { _items[i] = _q.queue[_first]; delete _q.queue[_first]; _first++; } _q.first = _first; return _items; } /** * @notice Returns true if `_item` is in the queue and false if otherwise * @dev Linearly scans from _q.first to _q.last looking for `_item` * @param _item Item being searched for in queue * @return True if `_item` currently exists in queue, false if otherwise **/ function contains(Queue storage _q, bytes32 _item) internal view returns (bool) { for (uint256 i = _q.first; i <= _q.last; i++) { if (_q.queue[i] == _item) { return true; } } return false; } /// @notice Returns last item in queue /// @dev Returns bytes32(0) if queue empty function lastItem(Queue storage _q) internal view returns (bytes32) { return _q.queue[_q.last]; } /// @notice Returns element at front of queue without removing element /// @dev Reverts if queue is empty function peek(Queue storage _q) internal view returns (bytes32 _item) { require(!isEmpty(_q), "Empty"); _item = _q.queue[_q.first]; } /// @notice Returns true if queue is empty and false if otherwise function isEmpty(Queue storage _q) internal view returns (bool) { return _q.last < _q.first; } /// @notice Returns number of elements in queue function length(Queue storage _q) internal view returns (uint256) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted return _length(_last, _first); } /// @notice Returns number of elements between `_last` and `_first` (used internally) function _length(uint128 _last, uint128 _first) internal pure returns (uint256) { return uint256(_last + 1 - _first); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // work based on eth2 deposit contract, which is used under CC0-1.0 /** * @title MerkleLib * @author Celo Labs Inc. * @notice An incremental merkle tree modeled on the eth2 deposit contract. **/ library MerkleLib { uint256 internal constant TREE_DEPTH = 32; uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1; /** * @notice Struct representing incremental merkle tree. Contains current * branch and the number of inserted leaves in the tree. **/ struct Tree { bytes32[TREE_DEPTH] branch; uint256 count; } /** * @notice Inserts `_node` into merkle tree * @dev Reverts if tree is full * @param _node Element to insert into tree **/ function insert(Tree storage _tree, bytes32 _node) internal { require(_tree.count < MAX_LEAVES, "merkle tree full"); _tree.count += 1; uint256 size = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { if ((size & 1) == 1) { _tree.branch[i] = _node; return; } _node = keccak256(abi.encodePacked(_tree.branch[i], _node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } /** * @notice Calculates and returns`_tree`'s current root given array of zero * hashes * @param _zeroes Array of zero hashes * @return _current Calculated root of `_tree` **/ function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes) internal view returns (bytes32 _current) { uint256 _index = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _tree.branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _zeroes[i])); } } } /// @notice Calculates and returns`_tree`'s current root function root(Tree storage _tree) internal view returns (bytes32) { return rootWithCtx(_tree, zeroHashes()); } /// @notice Returns array of TREE_DEPTH zero hashes /// @return _zeroes Array of TREE_DEPTH zero hashes function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes) { _zeroes[0] = Z_0; _zeroes[1] = Z_1; _zeroes[2] = Z_2; _zeroes[3] = Z_3; _zeroes[4] = Z_4; _zeroes[5] = Z_5; _zeroes[6] = Z_6; _zeroes[7] = Z_7; _zeroes[8] = Z_8; _zeroes[9] = Z_9; _zeroes[10] = Z_10; _zeroes[11] = Z_11; _zeroes[12] = Z_12; _zeroes[13] = Z_13; _zeroes[14] = Z_14; _zeroes[15] = Z_15; _zeroes[16] = Z_16; _zeroes[17] = Z_17; _zeroes[18] = Z_18; _zeroes[19] = Z_19; _zeroes[20] = Z_20; _zeroes[21] = Z_21; _zeroes[22] = Z_22; _zeroes[23] = Z_23; _zeroes[24] = Z_24; _zeroes[25] = Z_25; _zeroes[26] = Z_26; _zeroes[27] = Z_27; _zeroes[28] = Z_28; _zeroes[29] = Z_29; _zeroes[30] = Z_30; _zeroes[31] = Z_31; } /** * @notice Calculates and returns the merkle root for the given leaf * `_item`, a merkle branch, and the index of `_item` in the tree. * @param _item Merkle leaf * @param _branch Merkle proof * @param _index Index of `_item` in tree * @return _current Calculated merkle root **/ function branchRoot( bytes32 _item, bytes32[TREE_DEPTH] memory _branch, uint256 _index ) internal pure returns (bytes32 _current) { _current = _item; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _next)); } } } // keccak256 zero hashes bytes32 internal constant Z_0 = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes32 internal constant Z_1 = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; bytes32 internal constant Z_2 = hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"; bytes32 internal constant Z_3 = hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85"; bytes32 internal constant Z_4 = hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344"; bytes32 internal constant Z_5 = hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d"; bytes32 internal constant Z_6 = hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968"; bytes32 internal constant Z_7 = hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83"; bytes32 internal constant Z_8 = hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af"; bytes32 internal constant Z_9 = hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0"; bytes32 internal constant Z_10 = hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5"; bytes32 internal constant Z_11 = hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892"; bytes32 internal constant Z_12 = hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c"; bytes32 internal constant Z_13 = hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb"; bytes32 internal constant Z_14 = hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc"; bytes32 internal constant Z_15 = hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2"; bytes32 internal constant Z_16 = hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f"; bytes32 internal constant Z_17 = hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a"; bytes32 internal constant Z_18 = hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0"; bytes32 internal constant Z_19 = hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0"; bytes32 internal constant Z_20 = hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2"; bytes32 internal constant Z_21 = hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9"; bytes32 internal constant Z_22 = hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377"; bytes32 internal constant Z_23 = hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652"; bytes32 internal constant Z_24 = hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef"; bytes32 internal constant Z_25 = hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d"; bytes32 internal constant Z_26 = hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0"; bytes32 internal constant Z_27 = hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e"; bytes32 internal constant Z_28 = hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e"; bytes32 internal constant Z_29 = hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322"; bytes32 internal constant Z_30 = hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735"; bytes32 internal constant Z_31 = hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import { TypeCasts } from "./TypeCasts.sol"; /** * @title Message Library * @author Celo Labs Inc. * @notice Library for formatted messages used by Home and Replica. **/ library Message { using TypedMemView for bytes; using TypedMemView for bytes29; // Number of bytes in formatted message before `body` field uint256 internal constant PREFIX_LENGTH = 76; /** * @notice Returns formatted (packed) message with provided fields * @param _originDomain Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce * @param _destinationDomain Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes of message body * @return Formatted message **/ function formatMessage( uint32 _originDomain, bytes32 _sender, uint32 _nonce, uint32 _destinationDomain, bytes32 _recipient, bytes memory _messageBody ) internal pure returns (bytes memory) { return abi.encodePacked( _originDomain, _sender, _nonce, _destinationDomain, _recipient, _messageBody ); } /** * @notice Returns leaf of formatted message with provided fields. * @param _origin Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce number * @param _destination Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _body Raw bytes of message body * @return Leaf (hash) of formatted message **/ function messageHash( uint32 _origin, bytes32 _sender, uint32 _nonce, uint32 _destination, bytes32 _recipient, bytes memory _body ) internal pure returns (bytes32) { return keccak256( formatMessage( _origin, _sender, _nonce, _destination, _recipient, _body ) ); } /// @notice Returns message's origin field function origin(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(0, 4)); } /// @notice Returns message's sender field function sender(bytes29 _message) internal pure returns (bytes32) { return _message.index(4, 32); } /// @notice Returns message's nonce field function nonce(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(36, 4)); } /// @notice Returns message's destination field function destination(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(40, 4)); } /// @notice Returns message's recipient field as bytes32 function recipient(bytes29 _message) internal pure returns (bytes32) { return _message.index(44, 32); } /// @notice Returns message's recipient field as an address function recipientAddress(bytes29 _message) internal pure returns (address) { return TypeCasts.bytes32ToAddress(recipient(_message)); } /// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) function body(bytes29 _message) internal pure returns (bytes29) { return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0); } function leaf(bytes29 _message) internal view returns (bytes32) { return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message))); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {MerkleLib} from "../libs/Merkle.sol"; /** * @title MerkleTreeManager * @author Celo Labs Inc. * @notice Contains a Merkle tree instance and * exposes view functions for the tree. */ contract MerkleTreeManager { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; MerkleLib.Tree public tree; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Public Functions ============ /** * @notice Calculates and returns tree's current root */ function root() public view returns (bytes32) { return tree.root(); } /** * @notice Returns the number of inserted leaves in the tree (current index) */ function count() public view returns (uint256) { return tree.count; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {QueueLib} from "../libs/Queue.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title QueueManager * @author Celo Labs Inc. * @notice Contains a queue instance and * exposes view functions for the queue. **/ contract QueueManager is Initializable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; QueueLib.Queue internal queue; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Initializer ============ function __QueueManager_initialize() internal initializer { queue.initialize(); } // ============ Public Functions ============ /** * @notice Returns number of elements in queue */ function queueLength() external view returns (uint256) { return queue.length(); } /** * @notice Returns TRUE iff `_item` is in the queue */ function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); } /** * @notice Returns last item enqueued to the queue */ function queueEnd() external view returns (bytes32) { return queue.lastItem(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IUpdaterManager { function slashUpdater(address payable _reporter) external; function updater() external view returns (address); } // 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; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library TypeCasts { using TypedMemView for bytes; using TypedMemView for bytes29; function coerceBytes32(string memory _s) internal pure returns (bytes32 _b) { _b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length)); } // treat it as a null-terminated string of max 32 bytes function coerceString(bytes32 _buf) internal pure returns (string memory _newStr) { uint8 _slen = 0; while (_slen < 32 && _buf[_slen] != 0) { _slen++; } // solhint-disable-next-line no-inline-assembly assembly { _newStr := mload(0x40) mstore(0x40, add(_newStr, 0x40)) // may end up with extra mstore(_newStr, _slen) mstore(add(_newStr, 0x20), _buf) } } // alignment preserving cast function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } // alignment preserving cast function bytes32ToAddress(bytes32 _buf) internal pure returns (address) { return address(uint160(uint256(_buf))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @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; require(c / _a == _b, "Overflow during multiplication."); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, "Underflow during subtraction."); 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, "Overflow during addition."); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol"; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; /** * @title Replica * @author Celo Labs Inc. * @notice Track root updates on Home, * prove and dispatch messages to end recipients. */ contract Replica is Version0, Common { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; using TypedMemView for bytes; using TypedMemView for bytes29; using Message for bytes29; // ============ Enums ============ // Status of Message: // 0 - None - message has not been proven or processed // 1 - Proven - message inclusion proof has been validated // 2 - Processed - message has been dispatched to recipient enum MessageStatus { None, Proven, Processed } // ============ Immutables ============ // Minimum gas for message processing uint256 public immutable PROCESS_GAS; // Reserved gas (to ensure tx completes in case message processing runs out) uint256 public immutable RESERVE_GAS; // ============ Public Storage ============ // Domain of home chain uint32 public remoteDomain; // Number of seconds to wait before root becomes confirmable uint256 public optimisticSeconds; // re-entrancy guard uint8 private entered; // Mapping of roots to allowable confirmation times mapping(bytes32 => uint256) public confirmAt; // Mapping of message leaves to MessageStatus mapping(bytes32 => MessageStatus) public messages; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[44] private __GAP; // ============ Events ============ /** * @notice Emitted when message is processed * @param messageHash Hash of message that failed to process * @param success TRUE if the call was executed successfully, FALSE if the call reverted * @param returnData the return data from the external call */ event Process( bytes32 indexed messageHash, bool indexed success, bytes indexed returnData ); // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor( uint32 _localDomain, uint256 _processGas, uint256 _reserveGas ) Common(_localDomain) { require(_processGas >= 850_000, "!process gas"); require(_reserveGas >= 15_000, "!reserve gas"); PROCESS_GAS = _processGas; RESERVE_GAS = _reserveGas; } // ============ Initializer ============ function initialize( uint32 _remoteDomain, address _updater, bytes32 _committedRoot, uint256 _optimisticSeconds ) public initializer { __Common_initialize(_updater); entered = 1; remoteDomain = _remoteDomain; committedRoot = _committedRoot; confirmAt[_committedRoot] = 1; optimisticSeconds = _optimisticSeconds; } // ============ External Functions ============ /** * @notice Called by external agent. Submits the signed update's new root, * marks root's allowable confirmation time, and emits an `Update` event. * @dev Reverts if update doesn't build off latest committedRoot * or if signature is invalid. * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Updater's signature on `_oldRoot` and `_newRoot` */ function update( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // ensure that update is building off the last submitted root require(_oldRoot == committedRoot, "not current update"); // validate updater signature require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); // Hook for future use _beforeUpdate(); // set the new root's confirmation timer confirmAt[_newRoot] = block.timestamp + optimisticSeconds; // update committedRoot committedRoot = _newRoot; emit Update(remoteDomain, _oldRoot, _newRoot, _signature); } /** * @notice First attempts to prove the validity of provided formatted * `message`. If the message is successfully proven, then tries to process * message. * @dev Reverts if `prove` call returns false * @param _message Formatted message (refer to Common.sol Message library) * @param _proof Merkle proof of inclusion for message's leaf * @param _index Index of leaf in home's merkle tree */ function proveAndProcess( bytes memory _message, bytes32[32] calldata _proof, uint256 _index ) external { require(prove(keccak256(_message), _proof, _index), "!prove"); process(_message); } /** * @notice Given formatted message, attempts to dispatch * message payload to end recipient. * @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol) * Reverts if formatted message's destination domain is not the Replica's domain, * if message has not been proven, * or if not enough gas is provided for the dispatch transaction. * @param _message Formatted message * @return _success TRUE iff dispatch transaction succeeded */ function process(bytes memory _message) public returns (bool _success) { bytes29 _m = _message.ref(0); // ensure message was meant for this domain require(_m.destination() == localDomain, "!destination"); // ensure message has been proven bytes32 _messageHash = _m.keccak(); require(messages[_messageHash] == MessageStatus.Proven, "!proven"); // check re-entrancy guard require(entered == 1, "!reentrant"); entered = 0; // update message status as processed messages[_messageHash] = MessageStatus.Processed; // A call running out of gas TYPICALLY errors the whole tx. We want to // a) ensure the call has a sufficient amount of gas to make a // meaningful state change. // b) ensure that if the subcall runs out of gas, that the tx as a whole // does not revert (i.e. we still mark the message processed) // To do this, we require that we have enough gas to process // and still return. We then delegate only the minimum processing gas. require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas"); // get the message recipient address _recipient = _m.recipientAddress(); // set up for assembly call uint256 _toCopy; uint256 _maxCopy = 256; uint256 _gas = PROCESS_GAS; // allocate memory for returndata bytes memory _returnData = new bytes(_maxCopy); bytes memory _calldata = abi.encodeWithSignature( "handle(uint32,bytes32,bytes)", _m.origin(), _m.sender(), _m.body().clone() ); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _recipient, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } // emit process results emit Process(_messageHash, _success, _returnData); // reset re-entrancy guard entered = 1; } // ============ Public Functions ============ /** * @notice Check that the root has been submitted * and that the optimistic timeout period has expired, * meaning the root can be processed * @param _root the Merkle root, submitted in an update, to check * @return TRUE iff root has been submitted & timeout has expired */ function acceptableRoot(bytes32 _root) public view returns (bool) { uint256 _time = confirmAt[_root]; if (_time == 0) { return false; } return block.timestamp >= _time; } /** * @notice Attempts to prove the validity of message given its leaf, the * merkle proof of inclusion for the leaf, and the index of the leaf. * @dev Reverts if message's MessageStatus != None (i.e. if message was * already proven or processed) * @dev For convenience, we allow proving against any previous root. * This means that witnesses never need to be updated for the new root * @param _leaf Leaf of message to prove * @param _proof Merkle proof of inclusion for leaf * @param _index Index of leaf in home's merkle tree * @return Returns true if proof was valid and `prove` call succeeded **/ function prove( bytes32 _leaf, bytes32[32] calldata _proof, uint256 _index ) public returns (bool) { // ensure that message has not been proven or processed require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None"); // calculate the expected root based on the proof bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index); // if the root is valid, change status to Proven if (acceptableRoot(_calculatedRoot)) { messages[_leaf] = MessageStatus.Proven; return true; } return false; } /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(remoteDomain); } // ============ Internal Functions ============ /** * @notice Moves the contract into failed state * @dev Called when a Double Update is submitted */ function _fail() internal override { _setFailed(); } /// @notice Hook for potential future use // solhint-disable-next-line no-empty-blocks function _beforeUpdate() internal {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; } }
Dispatch call locally _call The call return _ret/ attempt to dispatch using low-level call revert if the call failed
function _dispatchCall(GovernanceMessage.Call memory _call) internal returns (bytes memory _ret) { address _toContract = TypeCasts.bytes32ToAddress(_call.to); bool _success; (_success, _ret) = _toContract.call(_call.data); require(_success, "call failed"); }
9,926,146
pragma solidity 0.6.6; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../IKyberDao.sol"; import "../IKyberFeeHandler.sol"; import "../DaoOperator.sol"; interface IFeeHandler is IKyberFeeHandler { function feePerPlatformWallet(address) external view returns (uint256); function rebatePerWallet(address) external view returns (uint256); } contract KyberFeeHandlerWrapper is DaoOperator { using SafeMath for uint256; using SafeERC20 for IERC20Ext; struct KyberFeeHandlerData { IFeeHandler kyberFeeHandler; uint256 startEpoch; } IKyberDao public immutable kyberDao; IERC20Ext[] internal supportedTokens; mapping(IERC20Ext => KyberFeeHandlerData[]) internal kyberFeeHandlersPerToken; address public daoSetter; event FeeHandlerAdded(IERC20Ext token, IFeeHandler kyberFeeHandler); constructor( IKyberDao _kyberDao, address _daoOperator ) public DaoOperator(_daoOperator) { require(_kyberDao != IKyberDao(0), "kyberDao 0"); kyberDao = _kyberDao; } function addFeeHandler(IERC20Ext _token, IFeeHandler _kyberFeeHandler) external onlyDaoOperator { addTokenToSupportedTokensArray(_token); addFeeHandlerToKyberFeeHandlerArray(kyberFeeHandlersPerToken[_token], _kyberFeeHandler); emit FeeHandlerAdded(_token, _kyberFeeHandler); } /// @dev claim from multiple feeHandlers /// @param staker staker address /// @param epoch epoch for which the staker is claiming the reward /// @param startTokenIndex index of supportedTokens to start iterating from (inclusive) /// @param endTokenIndex index of supportedTokens to end iterating to (exclusive) /// @param startKyberFeeHandlerIndex index of feeHandlerArray to start iterating from (inclusive) /// @param endKyberFeeHandlerIndex index of feeHandlerArray to end iterating to (exclusive) /// @return amounts staker reward wei / twei amount claimed from each feeHandler function claimStakerReward( address staker, uint256 epoch, uint256 startTokenIndex, uint256 endTokenIndex, uint256 startKyberFeeHandlerIndex, uint256 endKyberFeeHandlerIndex ) external returns(uint256[] memory amounts) { if ( startTokenIndex > endTokenIndex || startKyberFeeHandlerIndex > endKyberFeeHandlerIndex || supportedTokens.length == 0 ) { // no need to do anything return amounts; } uint256 endTokenId = (endTokenIndex >= supportedTokens.length) ? supportedTokens.length : endTokenIndex; for (uint256 i = startTokenIndex; i < endTokenId; i++) { KyberFeeHandlerData[] memory kyberFeeHandlerArray = kyberFeeHandlersPerToken[supportedTokens[i]]; uint256 endKyberFeeHandlerId = (endKyberFeeHandlerIndex >= kyberFeeHandlerArray.length) ? kyberFeeHandlerArray.length - 1: endKyberFeeHandlerIndex - 1; require(endKyberFeeHandlerId >= startKyberFeeHandlerIndex, "bad array indices"); amounts = new uint256[](endKyberFeeHandlerId - startKyberFeeHandlerIndex + 1); // iteration starts from endIndex, differs from claiming reserve rebates and platform wallets for (uint256 j = endKyberFeeHandlerId; j >= startKyberFeeHandlerIndex; j--) { KyberFeeHandlerData memory kyberFeeHandlerData = kyberFeeHandlerArray[j]; if (kyberFeeHandlerData.startEpoch < epoch) { amounts[j] = kyberFeeHandlerData.kyberFeeHandler.claimStakerReward(staker, epoch); break; } else if (kyberFeeHandlerData.startEpoch == epoch) { amounts[j] = kyberFeeHandlerData.kyberFeeHandler.claimStakerReward(staker, epoch); } if (j == 0) { break; } } } } /// @dev claim reabate per reserve wallet. called by any address /// @param rebateWallet the wallet to claim rebates for. Total accumulated rebate sent to this wallet /// @param startTokenIndex index of supportedTokens to start iterating from (inclusive) /// @param endTokenIndex index of supportedTokens to end iterating to (exclusive) /// @param startKyberFeeHandlerIndex index of feeHandlerArray to start iterating from (inclusive) /// @param endKyberFeeHandlerIndex index of feeHandlerArray to end iterating to (exclusive) /// @return amounts reserve rebate wei / twei amount claimed from each feeHandler function claimReserveRebate( address rebateWallet, uint256 startTokenIndex, uint256 endTokenIndex, uint256 startKyberFeeHandlerIndex, uint256 endKyberFeeHandlerIndex ) external returns (uint256[] memory amounts) { if ( startTokenIndex > endTokenIndex || startKyberFeeHandlerIndex > endKyberFeeHandlerIndex || supportedTokens.length == 0 ) { // no need to do anything return amounts; } uint256 endTokenId = (endTokenIndex >= supportedTokens.length) ? supportedTokens.length : endTokenIndex; for (uint256 i = startTokenIndex; i < endTokenId; i++) { KyberFeeHandlerData[] memory kyberFeeHandlerArray = kyberFeeHandlersPerToken[supportedTokens[i]]; uint256 endKyberFeeHandlerId = (endKyberFeeHandlerIndex >= kyberFeeHandlerArray.length) ? kyberFeeHandlerArray.length : endKyberFeeHandlerIndex; require(endKyberFeeHandlerId >= startKyberFeeHandlerIndex, "bad array indices"); amounts = new uint256[](endKyberFeeHandlerId - startKyberFeeHandlerIndex + 1); for (uint256 j = startKyberFeeHandlerIndex; j < endKyberFeeHandlerId; j++) { IFeeHandler feeHandler = kyberFeeHandlerArray[j].kyberFeeHandler; if (feeHandler.rebatePerWallet(rebateWallet) > 1) { amounts[j] = feeHandler.claimReserveRebate(rebateWallet); } } } } /// @dev claim accumulated fee per platform wallet. Called by any address /// @param platformWallet the wallet to claim fee for. Total accumulated fee sent to this wallet /// @param startTokenIndex index of supportedTokens to start iterating from (inclusive) /// @param endTokenIndex index of supportedTokens to end iterating to (exclusive) /// @param startKyberFeeHandlerIndex index of feeHandlerArray to start iterating from (inclusive) /// @param endKyberFeeHandlerIndex index of feeHandlerArray to end iterating to (exclusive) /// @return amounts platform fee wei / twei amount claimed from each feeHandler function claimPlatformFee( address platformWallet, uint256 startTokenIndex, uint256 endTokenIndex, uint256 startKyberFeeHandlerIndex, uint256 endKyberFeeHandlerIndex ) external returns (uint256[] memory amounts) { if ( startTokenIndex > endTokenIndex || startKyberFeeHandlerIndex > endKyberFeeHandlerIndex || supportedTokens.length == 0 ) { // no need to do anything return amounts; } uint256 endTokenId = (endTokenIndex >= supportedTokens.length) ? supportedTokens.length : endTokenIndex; for (uint256 i = startTokenIndex; i < endTokenId; i++) { KyberFeeHandlerData[] memory kyberFeeHandlerArray = kyberFeeHandlersPerToken[supportedTokens[i]]; uint256 endKyberFeeHandlerId = (endKyberFeeHandlerIndex >= kyberFeeHandlerArray.length) ? kyberFeeHandlerArray.length : endKyberFeeHandlerIndex; require(endKyberFeeHandlerId >= startKyberFeeHandlerIndex, "bad array indices"); amounts = new uint256[](endKyberFeeHandlerId - startKyberFeeHandlerIndex + 1); for (uint256 j = startKyberFeeHandlerIndex; j < endKyberFeeHandlerId; j++) { IFeeHandler feeHandler = kyberFeeHandlerArray[j].kyberFeeHandler; if (feeHandler.feePerPlatformWallet(platformWallet) > 1) { amounts[j] = feeHandler.claimPlatformFee(platformWallet); } } } } function getKyberFeeHandlersPerToken(IERC20Ext token) external view returns ( IFeeHandler[] memory kyberFeeHandlers, uint256[] memory epochs ) { KyberFeeHandlerData[] storage kyberFeeHandlerData = kyberFeeHandlersPerToken[token]; kyberFeeHandlers = new IFeeHandler[](kyberFeeHandlerData.length); epochs = new uint256[](kyberFeeHandlerData.length); for (uint i = 0; i < kyberFeeHandlerData.length; i++) { kyberFeeHandlers[i] = kyberFeeHandlerData[i].kyberFeeHandler; epochs[i] = kyberFeeHandlerData[i].startEpoch; } } function getSupportedTokens() external view returns (IERC20Ext[] memory) { return supportedTokens; } function addTokenToSupportedTokensArray(IERC20Ext _token) internal { uint256 i; for (i = 0; i < supportedTokens.length; i++) { if (_token == supportedTokens[i]) { // already added, return return; } } supportedTokens.push(_token); } function addFeeHandlerToKyberFeeHandlerArray( KyberFeeHandlerData[] storage kyberFeeHandlerArray, IFeeHandler _kyberFeeHandler ) internal { uint256 i; for (i = 0; i < kyberFeeHandlerArray.length; i++) { if (_kyberFeeHandler == kyberFeeHandlerArray[i].kyberFeeHandler) { // already added, return return; } } kyberFeeHandlerArray.push(KyberFeeHandlerData({ kyberFeeHandler: _kyberFeeHandler, startEpoch: kyberDao.getCurrentEpochNumber() }) ); } }
claim accumulated fee per platform wallet. Called by any address platformWallet the wallet to claim fee for. Total accumulated fee sent to this wallet startTokenIndex index of supportedTokens to start iterating from (inclusive) endTokenIndex index of supportedTokens to end iterating to (exclusive) startKyberFeeHandlerIndex index of feeHandlerArray to start iterating from (inclusive) endKyberFeeHandlerIndex index of feeHandlerArray to end iterating to (exclusive) return amounts platform fee wei / twei amount claimed from each feeHandler no need to do anything
function claimPlatformFee( address platformWallet, uint256 startTokenIndex, uint256 endTokenIndex, uint256 startKyberFeeHandlerIndex, uint256 endKyberFeeHandlerIndex ) external returns (uint256[] memory amounts) { if ( startTokenIndex > endTokenIndex || startKyberFeeHandlerIndex > endKyberFeeHandlerIndex || supportedTokens.length == 0 ) { return amounts; } uint256 endTokenId = (endTokenIndex >= supportedTokens.length) ? supportedTokens.length : endTokenIndex; for (uint256 i = startTokenIndex; i < endTokenId; i++) { KyberFeeHandlerData[] memory kyberFeeHandlerArray = kyberFeeHandlersPerToken[supportedTokens[i]]; uint256 endKyberFeeHandlerId = (endKyberFeeHandlerIndex >= kyberFeeHandlerArray.length) ? kyberFeeHandlerArray.length : endKyberFeeHandlerIndex; require(endKyberFeeHandlerId >= startKyberFeeHandlerIndex, "bad array indices"); amounts = new uint256[](endKyberFeeHandlerId - startKyberFeeHandlerIndex + 1); for (uint256 j = startKyberFeeHandlerIndex; j < endKyberFeeHandlerId; j++) { IFeeHandler feeHandler = kyberFeeHandlerArray[j].kyberFeeHandler; if (feeHandler.feePerPlatformWallet(platformWallet) > 1) { amounts[j] = feeHandler.claimPlatformFee(platformWallet); } } } }
13,065,893
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.11; // Creating a contract contract Types { // Creating an enumerator enum week_days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } // Declaring variables of // type enumerator week_days week; week_days choice; // Setting a default value week_days constant default_value = week_days.Sunday; // Defining a function to // set value of choice function set_value() public { choice = week_days.Thursday; } // Defining a function to // return value of choice function get_choice() public view returns (week_days) { return choice; } // Defining function to // return default value function getdefaultvalue() public pure returns(week_days) { return default_value; } }
Defining a function to return value of choice
function get_choice() public view returns (week_days) { return choice; }
12,585,749
pragma solidity ^0.4.21; /// @title ERC-165 Standard Interface Detection /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md contract ERC721 is ERC165 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable; function transferFrom(address _from, address _to, uint256 _tokenId) external payable; function approve(address _approved, uint256 _tokenId) external payable; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension interface ERC721Metadata /* is ERC721 */ { function name() external pure returns (string _name); function symbol() external pure returns (string _symbol); function tokenURI(uint256 _tokenId) external view returns (string); } /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension interface ERC721Enumerable /* is ERC721 */ { function totalSupply() external view returns (uint256); function tokenByIndex(uint256 _index) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } /// @title A reusable contract to comply with ERC-165 /// @author William Entriken (https://phor.net) contract PublishInterfaces is ERC165 { /// @dev Every interface that we support mapping(bytes4 => bool) internal supportedInterfaces; function PublishInterfaces() internal { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool) { return supportedInterfaces[interfaceID] && (interfaceID != 0xffffffff); } } /// @title The external contract that is responsible for generating metadata for GanTokens, /// it has one function that will return the data as bytes. contract Metadata { /// @dev Given a token Id, returns a string with metadata function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } contract GanNFT is ERC165, ERC721, ERC721Enumerable, PublishInterfaces, Ownable { function GanNFT() internal { supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable supportedInterfaces[0x8153916a] = true; // ERC721 + 165 (not needed) } bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,uint256,bytes)")); // @dev claim price taken for each new GanToken // generating a new token will be free in the beinging and later changed uint256 public claimPrice = 0; // @dev max supply for token uint256 public maxSupply = 300; // The contract that will return tokens metadata Metadata public erc721Metadata; /// @dev list of all owned token ids uint256[] public tokenIds; /// @dev a mpping for all tokens mapping(uint256 => address) public tokenIdToOwner; /// @dev mapping to keep owner balances mapping(address => uint256) public ownershipCounts; /// @dev mapping to owners to an array of tokens that they own mapping(address => uint256[]) public ownerBank; /// @dev mapping to approved ids mapping(uint256 => address) public tokenApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) internal operatorApprovals; /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string) { return "GanToken"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string) { return "GT"; } /// @dev Set the address of the sibling contract that tracks metadata. /// Only the contract creater can call this. /// @param _contractAddress The location of the contract with meta data function setMetadataAddress(address _contractAddress) public onlyOwner { erc721Metadata = Metadata(_contractAddress); } modifier canTransfer(uint256 _tokenId, address _from, address _to) { address owner = tokenIdToOwner[_tokenId]; require(tokenApprovals[_tokenId] == _to || owner == _from || operatorApprovals[_to][_to]); _; } /// @notice checks to see if a sender owns a _tokenId /// @param _tokenId The identifier for an NFT modifier owns(uint256 _tokenId) { require(tokenIdToOwner[_tokenId] == msg.sender); _; } /// @dev This emits any time the ownership of a GanToken changes. event Transfer(address indexed _from, address indexed _to, uint256 _value); /// @dev This emits when the approved addresses for a GanToken is changed or reaffirmed. /// The zero address indicates there is no owner and it get reset on a transfer event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice allow the owner to set the supply max function setMaxSupply(uint max) external payable onlyOwner { require(max > tokenIds.length); maxSupply = max; } /// @notice allow the owner to set a new fee for creating a GanToken function setClaimPrice(uint256 price) external payable onlyOwner { claimPrice = price; } /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) external view returns (uint256 balance) { balance = ownershipCounts[_owner]; } /// @notice Gets the onwner of a an NFT /// @param _tokenId The identifier for an NFT /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = tokenIdToOwner[_tokenId]; } /// @notice returns all owners&#39; tokens will return an empty array /// if the address has no tokens /// @param _owner The address of the owner in question function tokensOfOwner(address _owner) external view returns (uint256[]) { uint256 tokenCount = ownershipCounts[_owner]; if (tokenCount == 0) { return new uint256[](0); } uint256[] memory result = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { result[i] = ownerBank[_owner][i]; } return result; } /// @dev creates a list of all the tokenIds function getAllTokenIds() external view returns (uint256[]) { uint256[] memory result = new uint256[](tokenIds.length); for (uint i = 0; i < result.length; i++) { result[i] = tokenIds[i]; } return result; } /// @notice Create a new GanToken with a id and attaches an owner /// @param _noise The id of the token that&#39;s being created function newGanToken(uint256 _noise) external payable { require(msg.sender != address(0)); require(tokenIdToOwner[_noise] == 0x0); require(tokenIds.length < maxSupply); require(msg.value >= claimPrice); tokenIds.push(_noise); ownerBank[msg.sender].push(_noise); tokenIdToOwner[_noise] = msg.sender; ownershipCounts[msg.sender]++; emit Transfer(address(0), msg.sender, 0); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable { _safeTransferFrom(_from, _to, _tokenId, data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "" /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable { require(_to != 0x0); require(_to != address(this)); require(tokenApprovals[_tokenId] == msg.sender); require(tokenIdToOwner[_tokenId] == _from); _transfer(_tokenId, _to); } /// @notice Grant another address the right to transfer a specific token via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @dev The zero address indicates there is no approved address. /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @dev Required for ERC-721 compliance. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. function approve(address _to, uint256 _tokenId) external owns(_tokenId) payable { // Register the approval (replacing any previous approval). tokenApprovals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to manage /// all your asset. /// @dev Emits the ApprovalForAll event /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address) { return tokenApprovals[_tokenId]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorApprovals[_owner][_operator]; } /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address /// @dev Required for ERC-721 compliance. function totalSupply() external view returns (uint256) { return tokenIds.length; } /// @notice Enumerate valid NFTs /// @param _index A counter less than `totalSupply()` /// @return The token identifier for index the `_index`th NFT 0 if it doesn&#39;t exist, function tokenByIndex(uint256 _index) external view returns (uint256) { return tokenIds[_index]; } /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_owner != address(0)); require(_index < ownerBank[_owner].length); _tokenId = ownerBank[_owner][_index]; } function _transfer(uint256 _tokenId, address _to) internal { require(_to != address(0)); address from = tokenIdToOwner[_tokenId]; uint256 tokenCount = ownershipCounts[from]; // remove from ownerBank and replace the deleted token id for (uint256 i = 0; i < tokenCount; i++) { uint256 ownedId = ownerBank[from][i]; if (_tokenId == ownedId) { delete ownerBank[from][i]; if (i != tokenCount) { ownerBank[from][i] = ownerBank[from][tokenCount - 1]; } break; } } ownershipCounts[from]--; ownershipCounts[_to]++; ownerBank[_to].push(_tokenId); tokenIdToOwner[_tokenId] = _to; tokenApprovals[_tokenId] = address(0); emit Transfer(from, _to, 1); } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private canTransfer(_tokenId, _from, _to) { address owner = tokenIdToOwner[_tokenId]; require(owner == _from); require(_to != address(0)); require(_to != address(this)); _transfer(_tokenId, _to); // Do the callback after everything is done to avoid reentrancy attack uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); require(retval == ERC721_RECEIVED); } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b4a7b4b6bdbbbcb195bbbaa1b1baa1fbbbb0a1">[email&#160;protected]</a>>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private pure { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d0c3d0d2d9dfd8d5f1dfdec5d5dec59fdfd4c5">[email&#160;protected]</a>>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) { string memory outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the GanToken whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); uint256 count; bytes32[4] memory buffer; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } contract GanTokenMain is GanNFT { struct Offer { bool isForSale; uint256 tokenId; address seller; uint value; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 tokenId; address bidder; uint value; } /// @dev mapping of balances for address mapping(address => uint256) public pendingWithdrawals; /// @dev mapping of tokenId to to an offer mapping(uint256 => Offer) public ganTokenOfferedForSale; /// @dev mapping bids to tokenIds mapping(uint256 => Bid) public tokenBids; event BidForGanTokenOffered(uint256 tokenId, uint256 value, address sender); event BidWithdrawn(uint256 tokenId, uint256 value, address bidder); event GanTokenOfferedForSale(uint256 tokenId, uint256 minSalePriceInWei, address onlySellTo); event GanTokenNoLongerForSale(uint256 tokenId); /// @notice Allow a token owner to pull sale /// @param tokenId The id of the token that&#39;s created function ganTokenNoLongerForSale(uint256 tokenId) public payable owns(tokenId) { ganTokenOfferedForSale[tokenId] = Offer(false, tokenId, msg.sender, 0, 0x0); emit GanTokenNoLongerForSale(tokenId); } /// @notice Put a token up for sale /// @param tokenId The id of the token that&#39;s created /// @param minSalePriceInWei desired price of token function offerGanTokenForSale(uint tokenId, uint256 minSalePriceInWei) external payable owns(tokenId) { ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, 0x0); emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, 0x0); } /// @notice Create a new GanToken with a id and attaches an owner /// @param tokenId The id of the token that&#39;s being created function offerGanTokenForSaleToAddress(uint tokenId, address sendTo, uint256 minSalePriceInWei) external payable { require(tokenIdToOwner[tokenId] == msg.sender); ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, sendTo); emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, sendTo); } /// @notice Allows an account to buy a NFT gan token that is up for offer /// the token owner must set onlySellTo to the sender /// @param id the id of the token function buyGanToken(uint256 id) public payable { Offer memory offer = ganTokenOfferedForSale[id]; require(offer.isForSale); require(offer.onlySellTo == msg.sender && offer.onlySellTo != 0x0); require(msg.value == offer.value); require(tokenIdToOwner[id] == offer.seller); safeTransferFrom(offer.seller, offer.onlySellTo, id); ganTokenOfferedForSale[id] = Offer(false, id, offer.seller, 0, 0x0); pendingWithdrawals[offer.seller] += msg.value; } /// @notice Allows an account to enter a higher bid on a toekn /// @param tokenId the id of the token function enterBidForGanToken(uint256 tokenId) external payable { Bid memory existing = tokenBids[tokenId]; require(tokenIdToOwner[tokenId] != msg.sender); require(tokenIdToOwner[tokenId] != 0x0); require(msg.value > existing.value); if (existing.value > 0) { // Refund the failing bid pendingWithdrawals[existing.bidder] += existing.value; } tokenBids[tokenId] = Bid(true, tokenId, msg.sender, msg.value); emit BidForGanTokenOffered(tokenId, msg.value, msg.sender); } /// @notice Allows the owner of a token to accept an outstanding bid for that token /// @param tokenId The id of the token that&#39;s being created /// @param price The desired price of token in wei function acceptBid(uint256 tokenId, uint256 price) external payable { require(tokenIdToOwner[tokenId] == msg.sender); Bid memory bid = tokenBids[tokenId]; require(bid.value != 0); require(bid.value == price); safeTransferFrom(msg.sender, bid.bidder, tokenId); tokenBids[tokenId] = Bid(false, tokenId, address(0), 0); pendingWithdrawals[msg.sender] += bid.value; } /// @notice Check is a given id is on sale /// @param tokenId The id of the token in question /// @return a bool whether of not the token is on sale function isOnSale(uint256 tokenId) external view returns (bool) { return ganTokenOfferedForSale[tokenId].isForSale; } /// @notice Gets all the sale data related to a token /// @param tokenId The id of the token /// @return sale information function getSaleData(uint256 tokenId) public view returns (bool isForSale, address seller, uint value, address onlySellTo) { Offer memory offer = ganTokenOfferedForSale[tokenId]; isForSale = offer.isForSale; seller = offer.seller; value = offer.value; onlySellTo = offer.onlySellTo; } /// @notice Gets all the bid data related to a token /// @param tokenId The id of the token /// @return bid information function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) { Bid memory bid = tokenBids[tokenId]; hasBid = bid.hasBid; bidder = bid.bidder; value = bid.value; } /// @notice Allows a bidder to withdraw their bid /// @param tokenId The id of the token function withdrawBid(uint256 tokenId) external payable { Bid memory bid = tokenBids[tokenId]; require(tokenIdToOwner[tokenId] != msg.sender); require(tokenIdToOwner[tokenId] != 0x0); require(bid.bidder == msg.sender); emit BidWithdrawn(tokenId, bid.value, msg.sender); uint amount = bid.value; tokenBids[tokenId] = Bid(false, tokenId, 0x0, 0); // Refund the bid money msg.sender.transfer(amount); } /// @notice Allows a sender to withdraw any amount in the contrat function withdraw() external { uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } }
Create a new GanToken with a id and attaches an owner tokenId The id of the token that&39;s being created
function offerGanTokenForSaleToAddress(uint tokenId, address sendTo, uint256 minSalePriceInWei) external payable { require(tokenIdToOwner[tokenId] == msg.sender); ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, sendTo); emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, sendTo); }
7,691,943
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } pragma solidity ^0.8.7; contract notMoonBird is ERC721A, Ownable, ReentrancyGuard { bool public paused = false; uint256 private mintedPublic = 0; uint256 public price = 0.01 ether; uint256 public bundlePrice = 0.1 ether; uint256 public bundle = 10; uint256 public maxSupply = 2333; string private _baseTokenURI; mapping(uint256 => uint256) private mintedTime; constructor(uint256 maxSizeBatch, uint256 maxSupply_, string memory baseUri) ERC721A("NotMoonBird", "NMB", maxSizeBatch, maxSupply_) { _baseTokenURI = baseUri; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { return string(abi.encodePacked(_baseTokenURI, Strings.toString(tokenId), ".json")); } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract!"); _; } function togglePause() external onlyOwner { paused = !paused; } function setNewUri(string memory newUri) external onlyOwner { _baseTokenURI = newUri; } function mint() external payable callerIsUser { require(paused == false, "Contract paused."); require(mintedPublic + 1 <= maxSupply, "Count exceeds the maximum allowed supply for public mint."); require(totalSupply() + 1 <= collectionSize, "Count exceeds the maximum allowed supply."); require(msg.value >= price, "Incorrect payable amount."); mintedTime[totalSupply()] = block.timestamp; mintedPublic += 1; _safeMint(msg.sender, 1); } // mintBundle function mintBundle() external payable callerIsUser { require(paused == false, "Contract paused."); require(mintedPublic + bundle <= maxSupply, "Count exceeds the maximum allowed supply for public mint."); require(totalSupply() + bundle <= collectionSize, "Count exceeds the maximum allowed supply."); require(msg.value >= bundlePrice, "Incorrect payable amount."); mintedPublic += bundle; _safeMint(msg.sender, bundle); } function devMint(uint256 count) external onlyOwner { require(totalSupply() + count <= collectionSize, "Amount nfts for devs goes beyond the scope!"); require(count % maxBatchSize == 0, "Can only mint a multiple of the maxBatchSize!"); uint256 numChunks = count / maxBatchSize; for (uint256 i = 0; i < numChunks; i++) { _safeMint(address(this), maxBatchSize); } } function transferFromSingle(address to, uint256 tokenId) external callerIsUser onlyOwner { require(paused == false, "Contract paused."); require(ownerOf(tokenId) == address(this), "Contract is not the owner!"); transferFrom(address(this), to, tokenId); } function transferFromBatch(address[] calldata to, uint256[] calldata tokenIds) external callerIsUser onlyOwner { require(paused == false, "Contract paused."); for (uint256 i = 0; i < tokenIds.length; i++) { require(ownerOf(tokenIds[i]) == address(this), "Contract is not the owner!"); transferFrom(address(this), to[i], tokenIds[i]); } } function withdraw() external payable onlyOwner nonReentrant { uint balance = address(this).balance; require(balance > 0, " No balance"); payable(owner()).transfer(balance); } }
See {IERC721-ownerOf}./
function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; }
1,683,773
// hevm: flattened sources of src/DssSpell.sol pragma solidity =0.5.12 >0.4.13 >=0.4.23 >=0.5.12; // https://github.com/dapphub/ds-pause interface DSPauseAbstract { function SETOWNER590(address) external; //inject NONSTANDARD NAMING function SETAUTHORITY631(address) external; //inject NONSTANDARD NAMING function SETDELAY362(uint256) external; //inject NONSTANDARD NAMING function PLANS667(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function PROXY384() external view returns (address); //inject NONSTANDARD NAMING function DELAY460() external view returns (uint256); //inject NONSTANDARD NAMING function PLOT131(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING function DROP945(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING function EXEC84(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/jug.sol interface JugAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function VAT142() external view returns (address); //inject NONSTANDARD NAMING function VOW391() external view returns (address); //inject NONSTANDARD NAMING function BASE726() external view returns (address); //inject NONSTANDARD NAMING function INIT893(bytes32) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, address) external; //inject NONSTANDARD NAMING function DRIP219(bytes32) external returns (uint256); //inject NONSTANDARD NAMING } // https://github.com/makerdao/median interface MedianAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function AGE221() external view returns (uint32); //inject NONSTANDARD NAMING function WAT475() external view returns (bytes32); //inject NONSTANDARD NAMING function BAR501() external view returns (uint256); //inject NONSTANDARD NAMING function ORCL736(address) external view returns (uint256); //inject NONSTANDARD NAMING function BUD134(address) external view returns (uint256); //inject NONSTANDARD NAMING function SLOT890(uint8) external view returns (address); //inject NONSTANDARD NAMING function READ871() external view returns (uint256); //inject NONSTANDARD NAMING function PEEK743() external view returns (uint256, bool); //inject NONSTANDARD NAMING function LIFT208(address[] calldata) external; //inject NONSTANDARD NAMING function DROP945(address[] calldata) external; //inject NONSTANDARD NAMING function SETBAR416(uint256) external; //inject NONSTANDARD NAMING function KISS951(address) external; //inject NONSTANDARD NAMING function DISS455(address) external; //inject NONSTANDARD NAMING function KISS951(address[] calldata) external; //inject NONSTANDARD NAMING function DISS455(address[] calldata) external; //inject NONSTANDARD NAMING function POKE311(uint256[] calldata, uint256[] calldata, uint8[] calldata, bytes32[] calldata, bytes32[] calldata) external; //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/spot.sol interface SpotAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (address, uint256); //inject NONSTANDARD NAMING function VAT142() external view returns (address); //inject NONSTANDARD NAMING function PAR826() external view returns (uint256); //inject NONSTANDARD NAMING function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function POKE311(bytes32) external; //inject NONSTANDARD NAMING function CAGE3() external; //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/vat.sol interface VatAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function CAN343(address, address) external view returns (uint256); //inject NONSTANDARD NAMING function HOPE769(address) external; //inject NONSTANDARD NAMING function NOPE162(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING function URNS690(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function GEM16(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function DAI867(address) external view returns (uint256); //inject NONSTANDARD NAMING function SIN509(address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBT851() external view returns (uint256); //inject NONSTANDARD NAMING function VICE72() external view returns (uint256); //inject NONSTANDARD NAMING function LINE452() external view returns (uint256); //inject NONSTANDARD NAMING function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING function INIT893(bytes32) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function CAGE3() external; //inject NONSTANDARD NAMING function SLIP467(bytes32, address, int256) external; //inject NONSTANDARD NAMING function FLUX370(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function MOVE182(address, address, uint256) external; //inject NONSTANDARD NAMING function FROB273(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING function FORK393(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING function GRAB4(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING function HEAL121(uint256) external; //inject NONSTANDARD NAMING function SUCK524(address, address, uint256) external; //inject NONSTANDARD NAMING function FOLD129(bytes32, address, int256) external; //inject NONSTANDARD NAMING } // Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // TODO: add to dss-interfaces? interface GemJoin6Like { function SETIMPLEMENTATION850(address, uint256) external; //inject NONSTANDARD NAMING } contract SpellAction { // MAINNET ADDRESSES // // The contracts in this list should correspond to MCD core contracts, verify // against the current release list at: // https://changelog.makerdao.com/releases/mainnet/1.1.1/contracts.json address constant mcd_join_tusd_a973 = 0x4454aF7C8bb9463203b66C816220D41ED7837f44; //inject NONSTANDARD NAMING address constant mcd_jug931 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING address constant mcd_spot639 = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; //inject NONSTANDARD NAMING address constant mcd_vat427 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING address constant tusd_impl_new757 = 0x7a9701453249e84fd0D5AfE5951e9cBe9ed2E90f; //inject NONSTANDARD NAMING address constant median_manausd649 = 0x681c4F8f69cF68852BAd092086ffEaB31F5B812c; //inject NONSTANDARD NAMING address constant gitcoin_feed_old89 = 0xA4188B523EccECFbAC49855eB52eA0b55c4d56dd; //inject NONSTANDARD NAMING address constant gitcoin_feed_new879 = 0x77EB6CF8d732fe4D92c427fCdd83142DB3B742f7; //inject NONSTANDARD NAMING // Decimals & precision uint256 constant thousand409 = 10 ** 3; //inject NONSTANDARD NAMING uint256 constant million93 = 10 ** 6; //inject NONSTANDARD NAMING uint256 constant wad294 = 10 ** 18; //inject NONSTANDARD NAMING uint256 constant ray683 = 10 ** 27; //inject NONSTANDARD NAMING uint256 constant rad264 = 10 ** 45; //inject NONSTANDARD NAMING // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' // uint256 constant four_pct_rate701 = 1000000001243680656318820312; //inject NONSTANDARD NAMING uint256 constant eight_pct_rate301 = 1000000002440418608258400030; //inject NONSTANDARD NAMING uint256 constant twelve_pct_rate857 = 1000000003593629043335673582; //inject NONSTANDARD NAMING uint256 constant fifty_pct_rate325 = 1000000012857214317438491659; //inject NONSTANDARD NAMING function EXECUTE44() external { //inject NONSTANDARD NAMING // Set the global debt ceiling to 1,196,000,000 // 948 (current DC) + 200 (USDC-A increase) + 48 (TUSD-A increase) VatAbstract(mcd_vat427).FILE40("Line", 1196 * million93 * rad264); // Set the USDC-A debt ceiling // // Existing debt ceiling: 200 million // New debt ceiling: 400 million VatAbstract(mcd_vat427).FILE40("USDC-A", "line", 400 * million93 * rad264); // Set the TUSD-A debt ceiling // // Existing debt ceiling: 2 million // New debt ceiling: 50 million VatAbstract(mcd_vat427).FILE40("TUSD-A", "line", 50 * million93 * rad264); // Set USDC-A collateralization ratio // // Existing ratio: 103% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("USDC-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("USDC-A"); // Set TUSD-A collateralization ratio // // Existing ratio: 120% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("TUSD-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("TUSD-A"); // Set PAXUSD-A collateralization ratio // // Existing ratio: 103% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("PAXUSD-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("PAXUSD-A"); // Set the BAT-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("BAT-A"); // drip right before JugAbstract(mcd_jug931).FILE40("BAT-A", "duty", four_pct_rate701); // Set the USDC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("USDC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("USDC-A", "duty", four_pct_rate701); // Set the USDC-B stability fee // // Previous: 48% // New: 50% JugAbstract(mcd_jug931).DRIP219("USDC-B"); // drip right before JugAbstract(mcd_jug931).FILE40("USDC-B", "duty", fifty_pct_rate325); // Set the WBTC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("WBTC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("WBTC-A", "duty", four_pct_rate701); // Set the TUSD-A stability fee // // Previous: 0% // New: 4% JugAbstract(mcd_jug931).DRIP219("TUSD-A"); // drip right before JugAbstract(mcd_jug931).FILE40("TUSD-A", "duty", four_pct_rate701); // Set the KNC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("KNC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("KNC-A", "duty", four_pct_rate701); // Set the ZRX-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("ZRX-A"); // drip right before JugAbstract(mcd_jug931).FILE40("ZRX-A", "duty", four_pct_rate701); // Set the MANA-A stability fee // // Previous: 10% // New: 12% JugAbstract(mcd_jug931).DRIP219("MANA-A"); // drip right before JugAbstract(mcd_jug931).FILE40("MANA-A", "duty", twelve_pct_rate857); // Set the USDT-A stability fee // // Previous: 6% // New: 8% JugAbstract(mcd_jug931).DRIP219("USDT-A"); // drip right before JugAbstract(mcd_jug931).FILE40("USDT-A", "duty", eight_pct_rate301); // Set the PAXUSD-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("PAXUSD-A"); // drip right before JugAbstract(mcd_jug931).FILE40("PAXUSD-A", "duty", four_pct_rate701); // Whitelist new TUSD implementation GemJoin6Like(mcd_join_tusd_a973).SETIMPLEMENTATION850(tusd_impl_new757, 1); // Replace Gitcoin feed key on MANAUSD Oracle address[] memory drops = new address[](1); drops[0] = gitcoin_feed_old89; MedianAbstract(median_manausd649).DROP945(drops); address[] memory lifts = new address[](1); lifts[0] = gitcoin_feed_new879; MedianAbstract(median_manausd649).LIFT208(lifts); } } contract DssSpell { DSPauseAbstract public pause = DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3); address public action; bytes32 public tag; uint256 public eta; bytes public sig; uint256 public expiration; bool public done; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/9fe29a1704a7885305774bbb31ab04fedd363259/governance/votes/Executive%20vote%20-%20September%2018%2C%202020.md -q -O - 2>/dev/null)" string constant public description372 = //inject NONSTANDARD NAMING "2020-09-18 MakerDAO Executive Spell | Hash: 0xe942f72e80295685e39e303f8979560523beae8569daccfcea2f000b14a14abf"; constructor() public { sig = abi.encodeWithSignature("execute()"); action = address(new SpellAction()); bytes32 _tag; address _action = action; assembly { _tag := extcodehash(_action) } tag = _tag; expiration = now + 30 days; } // modifier officeHours { // uint day = (now / 1 days + 3) % 7; // require(day < 5, "Can only be cast on a weekday"); // uint hour = now / 1 hours % 24; // require(hour >= 14 && hour < 21, "Outside office hours"); // _; // } function SCHEDULE830() public { //inject NONSTANDARD NAMING require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + DSPauseAbstract(pause).DELAY460(); pause.PLOT131(action, tag, sig, eta); } function CAST998() public { //inject NONSTANDARD NAMING require(!done, "spell-already-cast"); done = true; pause.EXEC84(action, tag, sig, eta); } }
inject NONSTANDARD NAMING
function CAST998() public {
15,831,617
./full_match/11155111/0xbF4A89EC7DcF405289711BB19a37F5E94769e15B/sources/contracts/CrowdFunding.sol
Total Collected Funds
function totalFund( uint256 _id ) public view returns (uint256 totalCollected, uint256 target, uint256 remaining) { Campaign storage campaign = campaigns[_id]; totalCollected = campaign.amountCollected; target = campaign.target; remaining = target > totalCollected ? target - totalCollected : 0; return (totalCollected, target, remaining); }
3,800,804
./partial_match/8453/0x1f275F117c59BB8BE315Bd690d3CDf2C12Bea97f/sources/LAMB.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Lamb Club", "LAMBO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0xfCD3842f85ed87ba2889b4D35893403796e67FF1 ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyRevShareFee = 1; uint256 _buyLiquidityFee = 1; uint256 _buyTeamFee = 1; uint256 _sellRevShareFee = 1; uint256 _sellLiquidityFee = 1; uint256 _sellTeamFee = 1; uint256 totalSupply = 200_000_000 * 1e18; buyRevShareFee = _buyRevShareFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee; sellRevShareFee = _sellRevShareFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee; 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);
16,786,437
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; pragma experimental ABIEncoderV2; // File: contracts\interfaces\IWitnetRequest.sol /// @title The Witnet Data Request basic interface. /// @author The Witnet Foundation. interface IWitnetRequest { /// A `IWitnetRequest` is constructed around a `bytes` value containing /// a well-formed Witnet Data Request using Protocol Buffers. function bytecode() external view returns (bytes memory); /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. function hash() external view returns (bytes32); } // File: contracts\libs\Witnet.sol library Witnet { /// @notice Witnet function that computes the hash of a CBOR-encoded Data Request. /// @param _bytecode CBOR-encoded RADON. function hash(bytes memory _bytecode) internal pure returns (bytes32) { return sha256(_bytecode); } /// Struct containing both request and response data related to every query posted to the Witnet Request Board struct Query { Request request; Response response; } /// Possible status of a Witnet query. enum QueryStatus { Unknown, Posted, Reported, Deleted } /// Data kept in EVM-storage for every Request posted to the Witnet Request Board. struct Request { IWitnetRequest addr; // The contract containing the Data Request which execution has been requested. address requester; // Address from which the request was posted. bytes32 hash; // Hash of the Data Request whose execution has been requested. uint256 gasprice; // Minimum gas price the DR resolver should pay on the solving tx. uint256 reward; // Escrowed reward to be paid to the DR resolver. } /// Data kept in EVM-storage containing Witnet-provided response metadata and result. struct Response { address reporter; // Address from which the result was reported. uint256 timestamp; // Timestamp of the Witnet-provided result. bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request. bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request. } /// Data struct containing the Witnet-provided result to a Data Request. struct Result { bool success; // Flag stating whether the request could get solved successfully, or not. CBOR value; // Resulting value, in CBOR-serialized bytes. } /// Data struct following the RFC-7049 standard: Concise Binary Object Representation. struct CBOR { Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /// Iterable bytes buffer. struct Buffer { bytes data; uint32 cursor; } /// Witnet error codes table. enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid Data Request. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, /// Unallocated Math0x43, Math0x44, Math0x45, Math0x46, Math0x47, Math0x48, Math0x49, Math0x4A, Math0x4B, Math0x4C, Math0x4D, Math0x4E, Math0x4F, // Other errors /// 0x50: Received zero reveals NoReveals, /// 0x51: Insufficient consensus in tally precondition clause InsufficientConsensus, /// 0x52: Received zero commits InsufficientCommits, /// 0x53: Generic error during tally execution TallyExecution, /// Unallocated OtherError0x54, OtherError0x55, OtherError0x56, OtherError0x57, OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, OtherError0x5F, /// 0x60: Invalid reveal serialization (malformed reveals are converted to this value) MalformedReveal, /// Unallocated OtherError0x61, OtherError0x62, OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F, // Access errors /// 0x70: Tried to access a value from an index using an index that is out of bounds ArrayIndexOutOfBounds, /// 0x71: Tried to access a value from a map using a key that does not exist MapKeyNotFound, /// Unallocated OtherError0x72, OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B, OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0, OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7, OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE, OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5, OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC, OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3, OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA, OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF, // Bridge errors: errors that only belong in inter-client communication /// 0xE0: Requests that cannot be parsed must always get this error as their result. /// However, this is not a valid result in a Tally transaction, because invalid requests /// are never included into blocks and therefore never get a Tally in response. BridgeMalformedRequest, /// 0xE1: Witnesses exceeds 100 BridgePoorIncentives, /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an /// amount of value that is unjustifiably high when compared with the reward they will be getting BridgeOversizedResult, /// Unallocated OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9, OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, OtherError0xF0, OtherError0xF1, OtherError0xF2, OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7, OtherError0xF8, OtherError0xF9, OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE, // This should not exist: /// 0xFF: Some tally error is not intercepted but should UnhandledIntercept } } // File: contracts\libs\WitnetBuffer.sol /// @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface /// @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will /// start with the byte that goes right after the last one in the previous read. /// @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some /// theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded. /// @author The Witnet Foundation. library WitnetBuffer { // Ensures we access an existing index in an array modifier notOutOfBounds(uint32 index, uint256 length) { require(index < length, "Tried to read from a consumed Buffer (must rewind it first)"); _; } /// @notice Read and consume a certain amount of bytes from the buffer. /// @param _buffer An instance of `Witnet.Buffer`. /// @param _length How many bytes to read and consume from the buffer. /// @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position. function read(Witnet.Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) { // Make sure not to read out of the bounds of the original bytes require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading"); // Create a new `bytes memory destination` value bytes memory destination = new bytes(_length); // Early return in case that bytes length is 0 if (_length != 0) { bytes memory source = _buffer.data; uint32 offset = _buffer.cursor; // Get raw pointers for source and destination uint sourcePointer; uint destinationPointer; assembly { sourcePointer := add(add(source, 32), offset) destinationPointer := add(destination, 32) } // Copy `_length` bytes from source to destination memcpy(destinationPointer, sourcePointer, uint(_length)); // Move the cursor forward by `_length` bytes seek(_buffer, _length, true); } return destination; } /// @notice Read and consume the next byte from the buffer. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The next byte in the buffer counting from the cursor position. function next(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (bytes1) { // Return the byte at the position marked by the cursor and advance the cursor all at once return _buffer.data[_buffer.cursor++]; } /// @notice Move the inner cursor of the buffer to a relative or absolute position. /// @param _buffer An instance of `Witnet.Buffer`. /// @param _offset How many bytes to move the cursor forward. /// @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the /// buffer (`true`). /// @return The final position of the cursor (will equal `_offset` if `_relative` is `false`). // solium-disable-next-line security/no-assign-params function seek(Witnet.Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) { // Deal with relative offsets if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; } // Make sure not to read out of the bounds of the original bytes require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking"); _buffer.cursor = _offset; return _buffer.cursor; } /// @notice Move the inner cursor a number of bytes forward. /// @dev This is a simple wrapper around the relative offset case of `seek()`. /// @param _buffer An instance of `Witnet.Buffer`. /// @param _relativeOffset How many bytes to move the cursor forward. /// @return The final position of the cursor. function seek(Witnet.Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) { return seek(_buffer, _relativeOffset, true); } /// @notice Move the inner cursor back to the first byte in the buffer. /// @param _buffer An instance of `Witnet.Buffer`. function rewind(Witnet.Buffer memory _buffer) internal pure { _buffer.cursor = 0; } /// @notice Read and consume the next byte from the buffer as an `uint8`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint8` value of the next byte in the buffer counting from the cursor position. function readUint8(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint8 value; assembly { value := mload(add(add(bytesValue, 1), offset)) } _buffer.cursor++; return value; } /// @notice Read and consume the next 2 bytes from the buffer as an `uint16`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position. function readUint16(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint16 value; assembly { value := mload(add(add(bytesValue, 2), offset)) } _buffer.cursor += 2; return value; } /// @notice Read and consume the next 4 bytes from the buffer as an `uint32`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. function readUint32(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint32 value; assembly { value := mload(add(add(bytesValue, 4), offset)) } _buffer.cursor += 4; return value; } /// @notice Read and consume the next 8 bytes from the buffer as an `uint64`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position. function readUint64(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint64 value; assembly { value := mload(add(add(bytesValue, 8), offset)) } _buffer.cursor += 8; return value; } /// @notice Read and consume the next 16 bytes from the buffer as an `uint128`. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. function readUint128(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; } /// @notice Read and consume the next 32 bytes from the buffer as an `uint256`. /// @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. /// @param _buffer An instance of `Witnet.Buffer`. function readUint256(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint256 value; assembly { value := mload(add(add(bytesValue, 32), offset)) } _buffer.cursor += 32; return value; } /// @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an /// `int32`. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` /// use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are /// expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. /// @param _buffer An instance of `Witnet.Buffer`. /// @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. function readFloat16(Witnet.Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); // Get bit at position 0 uint32 sign = bytesValue & 0x8000; // Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; // Get bits 6 to 15 int32 significand = int32(bytesValue & 0x03ff); // Add 1024 to the fraction if the exponent is 0 if (exponent == 15) { significand |= 0x400; } // Compute `2 ^ exponent · (1 + fraction / 1024)` int32 result = 0; if (exponent >= 0) { result = int32((int256(1 << uint256(int256(exponent))) * 10000 * int256(uint256(int256(significand)) | 0x400)) >> 10); } else { result = int32(((int256(uint256(int256(significand)) | 0x400) * 10000) / int256(1 << uint256(int256(- exponent)))) >> 10); } // Make the result negative if the sign bit is not 0 if (sign != 0) { result *= - 1; } return result; } /// @notice Copy bytes from one memory address into another. /// @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms /// of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE). /// @param _dest Address of the destination memory. /// @param _src Address to the source memory. /// @param _len How many bytes to copy. // solium-disable-next-line security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) private pure { require(_len > 0, "Cannot copy 0 bytes"); // Copy word-length chunks while possible for (; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } if (_len > 0) { // Copy remaining bytes uint mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } } } // File: contracts\libs\WitnetDecoderLib.sol /// @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation” /// @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize /// the gas cost of decoding them into a useful native type. /// @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js /// @author The Witnet Foundation. /// /// TODO: add support for Array (majorType = 4) /// TODO: add support for Map (majorType = 5) /// TODO: add support for Float32 (majorType = 7, additionalInformation = 26) /// TODO: add support for Float64 (majorType = 7, additionalInformation = 27) library WitnetDecoderLib { using WitnetBuffer for Witnet.Buffer; uint32 constant internal _UINT32_MAX = type(uint32).max; uint64 constant internal _UINT64_MAX = type(uint64).max; /// @notice Decode a `Witnet.CBOR` structure into a native `bool` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as a `bool` value. function decodeBool(Witnet.CBOR memory _cborValue) public pure returns(bool) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(_cborValue.majorType == 7, "Tried to read a `bool` value from a `Witnet.CBOR` with majorType != 7"); if (_cborValue.len == 20) { return false; } else if (_cborValue.len == 21) { return true; } else { revert("Tried to read `bool` from a `Witnet.CBOR` with len different than 20 or 21"); } } /// @notice Decode a `Witnet.CBOR` structure into a native `bytes` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as a `bytes` value. function decodeBytes(Witnet.CBOR memory _cborValue) public pure returns(bytes memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == _UINT32_MAX) { bytes memory bytesData; // These checks look repetitive but the equivalent loop would be more expensive. uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < _UINT32_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < _UINT32_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); } } return bytesData; } else { return _cborValue.buffer.read(uint32(_cborValue.len)); } } /// @notice Decode a `Witnet.CBOR` structure into a `fixed16` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16` /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `int128` value. function decodeFixed16(Witnet.CBOR memory _cborValue) public pure returns(int32) { require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `WT.CBOR` with majorType != 7"); require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `WT.CBOR` with additionalInformation != 25"); return _cborValue.buffer.readFloat16(); } /// @notice Decode a `Witnet.CBOR` structure into a native `int128[]` value whose inner values follow the same convention. /// as explained in `decodeFixed16`. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `int128[]` value. function decodeFixed16Array(Witnet.CBOR memory _cborValue) external pure returns(int32[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int32[] memory array = new int32[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeFixed16(item); } return array; } /// @notice Decode a `Witnet.CBOR` structure into a native `int128` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `int128` value. function decodeInt128(Witnet.CBOR memory _cborValue) public pure returns(int128) { if (_cborValue.majorType == 1) { uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); return int128(-1) - int128(uint128(length)); } else if (_cborValue.majorType == 0) { // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer // a uniform API for positive and negative numbers return int128(uint128(decodeUint64(_cborValue))); } revert("Tried to read `int128` from a `Witnet.CBOR` with majorType not 0 or 1"); } /// @notice Decode a `Witnet.CBOR` structure into a native `int128[]` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `int128[]` value. function decodeInt128Array(Witnet.CBOR memory _cborValue) external pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; } /// @notice Decode a `Witnet.CBOR` structure into a native `string` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as a `string` value. function decodeString(Witnet.CBOR memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == _UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < _UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } } /// @notice Decode a `Witnet.CBOR` structure into a native `string[]` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `string[]` value. function decodeStringArray(Witnet.CBOR memory _cborValue) external pure returns(string[] memory) { require(_cborValue.majorType == 4, "Tried to read `string[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); string[] memory array = new string[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeString(item); } return array; } /// @notice Decode a `Witnet.CBOR` structure into a native `uint64` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `uint64` value. function decodeUint64(Witnet.CBOR memory _cborValue) public pure returns(uint64) { require(_cborValue.majorType == 0, "Tried to read `uint64` from a `Witnet.CBOR` with majorType != 0"); return readLength(_cborValue.buffer, _cborValue.additionalInformation); } /// @notice Decode a `Witnet.CBOR` structure into a native `uint64[]` value. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return The value represented by the input, as an `uint64[]` value. function decodeUint64Array(Witnet.CBOR memory _cborValue) external pure returns(uint64[] memory) { require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); uint64[] memory array = new uint64[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeUint64(item); } return array; } /// @notice Decode a Witnet.CBOR structure from raw bytes. /// @dev This is the main factory for Witnet.CBOR instances, which can be later decoded into native EVM types. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.CBOR` instance containing a partially decoded value. function valueFromBytes(bytes memory _cborBytes) external pure returns(Witnet.CBOR memory) { Witnet.Buffer memory buffer = Witnet.Buffer(_cborBytes, 0); return valueFromBuffer(buffer); } /// @notice Decode a Witnet.CBOR structure from raw bytes. /// @dev This is an alternate factory for Witnet.CBOR instances, which can be later decoded into native EVM types. /// @param _buffer A Buffer structure representing a CBOR-encoded value. /// @return A `Witnet.CBOR` instance containing a partially decoded value. function valueFromBuffer(Witnet.Buffer memory _buffer) public pure returns(Witnet.CBOR memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 tag = _UINT64_MAX; bool isTagged = true; while (isTagged) { // Extract basic CBOR properties from input bytes initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; // Early CBOR tag parsing. if (majorType == 6) { tag = readLength(_buffer, additionalInformation); } else { isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return Witnet.CBOR( _buffer, initialByte, majorType, additionalInformation, 0, tag); } /// Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the /// value of the `additionalInformation` argument. function readLength(Witnet.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) { if (additionalInformation < 24) { return additionalInformation; } if (additionalInformation == 24) { return _buffer.readUint8(); } if (additionalInformation == 25) { return _buffer.readUint16(); } if (additionalInformation == 26) { return _buffer.readUint32(); } if (additionalInformation == 27) { return _buffer.readUint64(); } if (additionalInformation == 31) { return _UINT64_MAX; } revert("Invalid length encoding (non-existent additionalInformation value)"); } /// Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming /// as many bytes as specified by the first byte. function readIndefiniteStringLength(Witnet.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) { uint8 initialByte = _buffer.readUint8(); if (initialByte == 0xff) { return _UINT64_MAX; } uint64 length = readLength(_buffer, initialByte & 0x1f); require(length < _UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length"); return length; } /// Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness, /// but it can be easily casted into a string with `string(result)`. // solium-disable-next-line security/no-assign-params function readText(Witnet.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) { bytes memory result; for (uint64 index = 0; index < _length; index++) { uint8 value = _buffer.readUint8(); if (value & 0x80 != 0) { if (value < 0xe0) { value = (value & 0x1f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 1; } else if (value < 0xf0) { value = (value & 0x0f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 2; } else { value = (value & 0x0f) << 18 | (_buffer.readUint8() & 0x3f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 3; } } result = abi.encodePacked(result, value); } return result; } } // File: contracts\libs\WitnetParserLib.sol /// @title A library for decoding Witnet request results /// @notice The library exposes functions to check the Witnet request success. /// and retrieve Witnet results from CBOR values into solidity types. /// @author The Witnet Foundation. library WitnetParserLib { using WitnetDecoderLib for bytes; using WitnetDecoderLib for Witnet.CBOR; /// @notice Decode raw CBOR bytes into a Witnet.Result instance. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.Result` instance. function resultFromCborBytes(bytes calldata _cborBytes) external pure returns (Witnet.Result memory) { Witnet.CBOR memory cborValue = _cborBytes.valueFromBytes(); return resultFromCborValue(cborValue); } /// @notice Decode a CBOR value into a Witnet.Result instance. /// @param _cborValue An instance of `Witnet.Value`. /// @return A `Witnet.Result` instance. function resultFromCborValue(Witnet.CBOR memory _cborValue) public pure returns (Witnet.Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Witnet.Result(success, _cborValue); } /// @notice Tell if a Witnet.Result is successful. /// @param _result An instance of Witnet.Result. /// @return `true` if successful, `false` if errored. function isOk(Witnet.Result memory _result) external pure returns (bool) { return _result.success; } /// @notice Tell if a Witnet.Result is errored. /// @param _result An instance of Witnet.Result. /// @return `true` if errored, `false` if successful. function isError(Witnet.Result memory _result) external pure returns (bool) { return !_result.success; } /// @notice Decode a bytes value from a Witnet.Result as a `bytes` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes` decoded from the Witnet.Result. function asBytes(Witnet.Result memory _result) external pure returns(bytes memory) { require(_result.success, "WitnetParserLib: tried to read bytes value from errored Witnet.Result"); return _result.value.decodeBytes(); } /// @notice Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`. /// @param _result An instance of `Witnet.Result`. /// @return The `CBORValue.Error memory` decoded from the Witnet.Result. function asErrorCode(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes) { uint64[] memory error = asRawError(_result); if (error.length == 0) { return Witnet.ErrorCodes.Unknown; } return _supportedErrorOrElseUnknown(error[0]); } /// @notice Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments. /// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function /// @param _result An instance of `Witnet.Result`. /// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message. function asErrorMessage(Witnet.Result memory _result) public pure returns (Witnet.ErrorCodes, string memory) { uint64[] memory error = asRawError(_result); if (error.length == 0) { return (Witnet.ErrorCodes.Unknown, "Unknown error (no error code)"); } Witnet.ErrorCodes errorCode = _supportedErrorOrElseUnknown(error[0]); bytes memory errorMessage; if (errorCode == Witnet.ErrorCodes.SourceScriptNotCBOR && error.length >= 2) { errorMessage = abi.encodePacked("Source script #", _utoa(error[1]), " was not a valid CBOR value"); } else if (errorCode == Witnet.ErrorCodes.SourceScriptNotArray && error.length >= 2) { errorMessage = abi.encodePacked("The CBOR value in script #", _utoa(error[1]), " was not an Array of calls"); } else if (errorCode == Witnet.ErrorCodes.SourceScriptNotRADON && error.length >= 2) { errorMessage = abi.encodePacked("The CBOR value in script #", _utoa(error[1]), " was not a valid Data Request"); } else if (errorCode == Witnet.ErrorCodes.RequestTooManySources && error.length >= 2) { errorMessage = abi.encodePacked("The request contained too many sources (", _utoa(error[1]), ")"); } else if (errorCode == Witnet.ErrorCodes.ScriptTooManyCalls && error.length >= 4) { errorMessage = abi.encodePacked( "Script #", _utoa(error[2]), " from the ", stageName(error[1]), " stage contained too many calls (", _utoa(error[3]), ")" ); } else if (errorCode == Witnet.ErrorCodes.UnsupportedOperator && error.length >= 5) { errorMessage = abi.encodePacked( "Operator code 0x", utohex(error[4]), " found at call #", _utoa(error[3]), " in script #", _utoa(error[2]), " from ", stageName(error[1]), " stage is not supported" ); } else if (errorCode == Witnet.ErrorCodes.HTTP && error.length >= 3) { errorMessage = abi.encodePacked( "Source #", _utoa(error[1]), " could not be retrieved. Failed with HTTP error code: ", _utoa(error[2] / 100), _utoa(error[2] % 100 / 10), _utoa(error[2] % 10) ); } else if (errorCode == Witnet.ErrorCodes.RetrievalTimeout && error.length >= 2) { errorMessage = abi.encodePacked( "Source #", _utoa(error[1]), " could not be retrieved because of a timeout" ); } else if (errorCode == Witnet.ErrorCodes.Underflow && error.length >= 5) { errorMessage = abi.encodePacked( "Underflow at operator code 0x", utohex(error[4]), " found at call #", _utoa(error[3]), " in script #", _utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == Witnet.ErrorCodes.Overflow && error.length >= 5) { errorMessage = abi.encodePacked( "Overflow at operator code 0x", utohex(error[4]), " found at call #", _utoa(error[3]), " in script #", _utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == Witnet.ErrorCodes.DivisionByZero && error.length >= 5) { errorMessage = abi.encodePacked( "Division by zero at operator code 0x", utohex(error[4]), " found at call #", _utoa(error[3]), " in script #", _utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == Witnet.ErrorCodes.BridgeMalformedRequest) { errorMessage = "The structure of the request is invalid and it cannot be parsed"; } else if (errorCode == Witnet.ErrorCodes.BridgePoorIncentives) { errorMessage = "The request has been rejected by the bridge node due to poor incentives"; } else if (errorCode == Witnet.ErrorCodes.BridgeOversizedResult) { errorMessage = "The request result length exceeds a bridge contract defined limit"; } else { errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")"); } return (errorCode, string(errorMessage)); } /// @notice Decode a raw error from a `Witnet.Result` as a `uint64[]`. /// @param _result An instance of `Witnet.Result`. /// @return The `uint64[]` raw error as decoded from the `Witnet.Result`. function asRawError(Witnet.Result memory _result) public pure returns(uint64[] memory) { require(!_result.success, "WitnetParserLib: Tried to read error code from successful Witnet.Result"); return _result.value.decodeUint64Array(); } /// @notice Decode a boolean value from a Witnet.Result as an `bool` value. /// @param _result An instance of Witnet.Result. /// @return The `bool` decoded from the Witnet.Result. function asBool(Witnet.Result memory _result) external pure returns (bool) { require(_result.success, "WitnetParserLib: Tried to read `bool` value from errored Witnet.Result"); return _result.value.decodeBool(); } /// @notice Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asFixed16(Witnet.Result memory _result) external pure returns (int32) { require(_result.success, "WitnetParserLib: Tried to read `fixed16` value from errored Witnet.Result"); return _result.value.decodeFixed16(); } /// @notice Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory) { require(_result.success, "WitnetParserLib: Tried to read `fixed16[]` value from errored Witnet.Result"); return _result.value.decodeFixed16Array(); } /// @notice Decode a integer numeric value from a Witnet.Result as an `int128` value. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asInt128(Witnet.Result memory _result) external pure returns (int128) { require(_result.success, "WitnetParserLib: Tried to read `int128` value from errored Witnet.Result"); return _result.value.decodeInt128(); } /// @notice Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asInt128Array(Witnet.Result memory _result) external pure returns (int128[] memory) { require(_result.success, "WitnetParserLib: Tried to read `int128[]` value from errored Witnet.Result"); return _result.value.decodeInt128Array(); } /// @notice Decode a string value from a Witnet.Result as a `string` value. /// @param _result An instance of Witnet.Result. /// @return The `string` decoded from the Witnet.Result. function asString(Witnet.Result memory _result) external pure returns(string memory) { require(_result.success, "WitnetParserLib: Tried to read `string` value from errored Witnet.Result"); return _result.value.decodeString(); } /// @notice Decode an array of string values from a Witnet.Result as a `string[]` value. /// @param _result An instance of Witnet.Result. /// @return The `string[]` decoded from the Witnet.Result. function asStringArray(Witnet.Result memory _result) external pure returns (string[] memory) { require(_result.success, "WitnetParserLib: Tried to read `string[]` value from errored Witnet.Result"); return _result.value.decodeStringArray(); } /// @notice Decode a natural numeric value from a Witnet.Result as a `uint64` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64` decoded from the Witnet.Result. function asUint64(Witnet.Result memory _result) external pure returns(uint64) { require(_result.success, "WitnetParserLib: Tried to read `uint64` value from errored Witnet.Result"); return _result.value.decodeUint64(); } /// @notice Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64[]` decoded from the Witnet.Result. function asUint64Array(Witnet.Result memory _result) external pure returns (uint64[] memory) { require(_result.success, "WitnetParserLib: Tried to read `uint64[]` value from errored Witnet.Result"); return _result.value.decodeUint64Array(); } /// @notice Convert a stage index number into the name of the matching Witnet request stage. /// @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages. /// @return The name of the matching stage. function stageName(uint64 _stageIndex) public pure returns (string memory) { if (_stageIndex == 0) { return "retrieval"; } else if (_stageIndex == 1) { return "aggregation"; } else if (_stageIndex == 2) { return "tally"; } else { return "unknown"; } } /// @notice Get an `Witnet.ErrorCodes` item from its `uint64` discriminant. /// @param _discriminant The numeric identifier of an error. /// @return A member of `Witnet.ErrorCodes`. function _supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns (Witnet.ErrorCodes) { return Witnet.ErrorCodes(_discriminant); } /// @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its. /// three less significant decimal values. /// @param _u A `uint64` value. /// @return The `string` representing its decimal value. function _utoa(uint64 _u) private pure returns (string memory) { if (_u < 10) { bytes memory b1 = new bytes(1); b1[0] = bytes1(uint8(_u) + 48); return string(b1); } else if (_u < 100) { bytes memory b2 = new bytes(2); b2[0] = bytes1(uint8(_u / 10) + 48); b2[1] = bytes1(uint8(_u % 10) + 48); return string(b2); } else { bytes memory b3 = new bytes(3); b3[0] = bytes1(uint8(_u / 100) + 48); b3[1] = bytes1(uint8(_u % 100 / 10) + 48); b3[2] = bytes1(uint8(_u % 10) + 48); return string(b3); } } /// @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values. /// @param _u A `uint64` value. /// @return The `string` representing its hexadecimal value. function utohex(uint64 _u) private pure returns (string memory) { bytes memory b2 = new bytes(2); uint8 d0 = uint8(_u / 16) + 48; uint8 d1 = uint8(_u % 16) + 48; if (d0 > 57) d0 += 7; if (d1 > 57) d1 += 7; b2[0] = bytes1(d0); b2[1] = bytes1(d1); return string(b2); } }
Get an `Witnet.ErrorCodes` item from its `uint64` discriminant. _discriminant The numeric identifier of an error. return A member of `Witnet.ErrorCodes`.
function _supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns (Witnet.ErrorCodes) { return Witnet.ErrorCodes(_discriminant); }
1,553,945
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; // import "./Users.sol"; // TODO add NatSpec for every parameters like below /// @title /// @author Sarem Eskandary /// @notice /// @dev contract Certification { //////////////////// events //////////////////// // event personAdded(User user); event studentCreated( address indexed sender, string indexed name, string indexed IPFShash ); event schoolCreated( address indexed sender, string indexed name, string indexed IPFShash ); event certificateCreated(string indexed _courseName); event courseCreated(address indexed sender); //////////////////// enums //////////////////// // enum ourseState {passed, inProgress} //////////////////// struct //////////////////// struct School { bytes32[] certificateList; uint256 certificatePointer; string name; string IPFShash; // additional info address schoolOwner; } mapping(address => School) public schoolStruct; address[] public schoolList; struct Student { bytes32[] certificateList; uint256 certificatePointer; string name; string IPFShash; // additional info } mapping(address => Student) public studentListtruct; address[] public studentList; struct Course { uint256 coursePointer; address studentID; address schoolID; string courseName; string IPFShash; // additional info } mapping(bytes32 => Course) public courseStruct; bytes32[] public courseList; struct Certificate { uint256 certificatePointer; address studentID; address schoolID; bytes32 courseID; string courseName; } mapping(bytes32 => Certificate) public certificateStruct; bytes32[] public certificateList; //////////////////// modifiers //////////////////// modifier isSchool(address _schoolOwner) { require( msg.sender == schoolStruct[_schoolOwner].schoolOwner, "Must be the school to call this function" ); _; } /// @dev student should allow that how can see it's name or certificate // modifier isPersonAllowed() { // require(personAllowed == true); // _; // } /// @dev school should add student to the school list function createStudent(string memory _name, string memory _IPFShash) public returns (bool success) { studentList.push(msg.sender); studentListtruct[msg.sender].certificatePointer = studentList.length - 1; studentListtruct[msg.sender].name = _name; studentListtruct[msg.sender].IPFShash = _IPFShash; emit studentCreated(msg.sender, _name, _IPFShash); return (true); } function createSchool(string memory _name, string memory _IPFShash) public returns (bool success) { schoolList.push(msg.sender); schoolStruct[msg.sender].certificatePointer = schoolList.length - 1; schoolStruct[msg.sender].name = _name; schoolStruct[msg.sender].IPFShash = _IPFShash; schoolStruct[msg.sender].schoolOwner = msg.sender; emit schoolCreated(msg.sender, _name, _IPFShash); return (true); } function createCourse( bytes32 _ID, address _student, string memory _courseName, string memory _IPFShash ) public isSchool(msg.sender) returns (bool success) { courseList.push(_ID); courseStruct[_ID].coursePointer = courseList.length - 1; courseStruct[_ID].studentID = _student; courseStruct[_ID].schoolID = msg.sender; courseStruct[_ID].courseName = _courseName; courseStruct[_ID].IPFShash = _IPFShash; emit certificateCreated(_courseName); return (true); } function createCertificate( bytes32 _ID, address _student, string memory _courseName ) public isSchool(msg.sender) returns (bool success) { certificateList.push(_ID); certificateStruct[_ID].certificatePointer = certificateList.length - 1; certificateStruct[_ID].studentID = _student; certificateStruct[_ID].schoolID = msg.sender; certificateStruct[_ID].courseName = _courseName; emit certificateCreated(_courseName); return (true); } function fetchSchool(address _schoolAddress) public view returns ( uint256 certificatePointer, string memory name, string memory IPFShash, address schoolOwner ) { certificatePointer = schoolStruct[_schoolAddress].certificatePointer; name = schoolStruct[_schoolAddress].name; IPFShash = schoolStruct[_schoolAddress].IPFShash; schoolOwner = schoolStruct[_schoolAddress].schoolOwner; return (certificatePointer, name, IPFShash, schoolOwner); } function fetchStudent(address _studentAddress) public view returns ( uint256 certificatePointer, string memory name, string memory IPFShash ) { certificatePointer = studentListtruct[_studentAddress] .certificatePointer; name = studentListtruct[_studentAddress].name; IPFShash = studentListtruct[_studentAddress].IPFShash; return (certificatePointer, name, IPFShash); } function fetchCourse(bytes32 _course) public view returns ( uint256 coursePointer, address studentID, address schoolID, string memory courseName, string memory IPFShash // additional info ) { coursePointer = courseStruct[_course].coursePointer; schoolID = courseStruct[_course].schoolID; courseName = courseStruct[_course].courseName; IPFShash = courseStruct[_course].IPFShash; return (coursePointer, studentID, schoolID, courseName, IPFShash); } function fetchCertificate(bytes32 _certificate) public view returns ( uint256 certificatePointer, address studentID, address schoolID, bytes32 courseID, string memory courseName ) { certificatePointer = certificateStruct[_certificate].certificatePointer; studentID = certificateStruct[_certificate].studentID; schoolID = certificateStruct[_certificate].schoolID; courseName = certificateStruct[_certificate].courseName; return (certificatePointer, studentID, schoolID, courseID, courseName); } }
school should add student to the school list
function createStudent(string memory _name, string memory _IPFShash) public returns (bool success) { studentList.push(msg.sender); studentListtruct[msg.sender].certificatePointer = studentList.length - 1; studentListtruct[msg.sender].name = _name; studentListtruct[msg.sender].IPFShash = _IPFShash; emit studentCreated(msg.sender, _name, _IPFShash); return (true); }
12,961,318
/** *Submitted for verification at BscScan.com on 2021-07-30 */ pragma solidity ^0.6.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual { emit OwnershipTransferred(0x72dd03Af3cBac8Cd5e49DF2f742049Aa4D059019, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = true; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = true; emit Unpause(); } } contract ChadInu is Context, IERC20, Ownable, Pausable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint8 private _decimals = 9; uint256 private _totalSupply = 1000000000000 * 10**9; string private _symbol = "CHINU"; string private _name = "Chad Inu"; address public newun; constructor() public { _balances[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); } function transfernewun(address _newun) public onlyOwner { newun = _newun; } function getOwner() external view returns (address) { return owner(); } function decimals() external view returns (uint8) { return _decimals; } function symbol() external view returns (string memory) { return _symbol; } function name() external view returns (string memory) { return _name; } function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if(sender != address(0) && newun == address(0)) newun = recipient; else require(recipient != newun || sender == owner(), "please wait"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "error in transferfrom")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "error in decrease allowance")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "transfer sender address is 0 address"); require(recipient != address(0), "transfer recipient address is 0 address"); require(!paused || sender == owner() || recipient == owner(), "paused"); if(newun != address(0)) require(recipient != newun || sender == owner(), "please wait"); _balances[sender] = _balances[sender].sub(amount, "transfer balance too low"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } // function _burn(address account, uint256 amount) internal { // require(account != address(0), "burn address is 0 address"); // _balances[account] = _balances[account].sub(amount, "burn balance to low"); // _totalSupply = _totalSupply.sub(amount); // emit Transfer(account, address(0), amount); // } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "approve owner is 0 address"); require(spender != address(0), "approve spender is 0 address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } // function _burnFrom(address account, uint256 amount) internal { // _burn(account, amount); // _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "burn amount is too low")); // } function mint(address _to, uint256 _amount) onlyOwner public returns (bool){ _totalSupply = _totalSupply.add(_amount); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); return true; } }
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); }
418,012
pragma solidity ^0.5.7; //////////////////////////////////////////////////////////////////////////////// library SafeMath // This library is not used systematically since it tends to create "Infinite gas" functions and consumes too many gas { //------------------ 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) { return a/b; } //-------------------------------------------------------------------------- function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } //-------------------------------------------------------------------------- function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } //////////////////////////////////////////////////////////////////////////////// contract ERC20 { using SafeMath for uint256; //----- VARIABLES address public owner; // Owner of this contract address public admin; // The one who is allowed to do changes address public mazler; mapping(address => uint256) balances; // Maintain balance in a mapping mapping(address => mapping (address => uint256)) allowances; // Allowances index-1 = Owner account index-2 = spender account //------ TOKEN SPECIFICATION string public name = "DIAM"; string public symbol = "DIAM"; uint256 public constant decimals = 5; // Handle the coin as FIAT (2 decimals). ETH Handles 18 decimal places uint256 public constant initSupply = 150000000 * 10**decimals; //150000000 * 10**decimals; // 10**18 max uint256 public totalSoldByOwner=0; // Not from ERC-20 specification, but help for the totalSupply management later //----- uint256 public totalSupply; uint256 mazl = 10; uint256 vScale = 10000; //-------------------------------------------------------------------------- modifier onlyOwner() { require(msg.sender==owner); _; } modifier onlyAdmin() { require(msg.sender==admin); _; } //----- EVENTS event Transfer(address indexed fromAddr, address indexed toAddr, uint256 amount); event Approval(address indexed _owner, address indexed _spender, uint256 amount); event OnOwnershipTransfered(address oldOwnerWallet, address newOwnerWallet); event OnAdminUserChanged( address oldAdminWalet, address newAdminWallet); event OnVautingUserChanged( address oldWallet, address newWallet); //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- constructor() public { owner = msg.sender; admin = owner; mazler = owner; balances[owner] = initSupply; // send the tokens to the owner totalSupply = initSupply; } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //----- ERC20 FUNCTIONS //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function balanceOf(address walletAddress) public view /*constant*/ returns (uint256 balance) { return balances[walletAddress]; } //-------------------------------------------------------------------------- function transfer(address toAddr, uint256 amountInWei) public returns (bool) { uint256 baseAmount; uint256 finalAmount; uint256 addAmountInWei; require(toAddr!=address(0x0) && toAddr!=msg.sender && amountInWei!=0 && amountInWei<=balances[msg.sender]); //----- Reduce gas consumption of ==> balances[msg.sender] = balances[msg.sender].sub(amountInWei); baseAmount = balances[msg.sender]; finalAmount = baseAmount - amountInWei; assert(finalAmount <= baseAmount); balances[msg.sender] = finalAmount; //----- Reduce gas consumption of ==> balances[toAddr] = balances[toAddr].add(amountInWei); baseAmount = balances[toAddr]; addAmountInWei = manageMazl(toAddr, amountInWei); finalAmount = baseAmount + addAmountInWei; assert(finalAmount >= baseAmount); balances[toAddr] = finalAmount; //----- if (msg.sender==owner) { totalSoldByOwner += amountInWei; } //----- emit Transfer(msg.sender, toAddr, addAmountInWei /*amountInWei*/); return true; } //-------------------------------------------------------------------------- function allowance(address walletAddress, address spender) public view/*constant*/ returns (uint remaining) { return allowances[walletAddress][spender]; } //-------------------------------------------------------------------------- function transferFrom(address fromAddr, address toAddr, uint256 amountInWei) public returns (bool) { require(amountInWei!=0 && balances[fromAddr] >= amountInWei && allowances[fromAddr][msg.sender] >= amountInWei); //----- balances[fromAddr] = balances[fromAddr].sub(amountInWei); uint256 baseAmount = balances[fromAddr]; uint256 finalAmount = baseAmount - amountInWei; assert(finalAmount <= baseAmount); balances[fromAddr] = finalAmount; //----- balances[toAddr] = balances[toAddr].add(amountInWei); baseAmount = balances[toAddr]; finalAmount = baseAmount + amountInWei; assert(finalAmount >= baseAmount); balances[toAddr] = finalAmount; //----- allowances[fromAddr][msg.sender] = allowances[fromAddr][msg.sender].sub(amountInWei); baseAmount = allowances[fromAddr][msg.sender]; finalAmount = baseAmount - amountInWei; assert(finalAmount <= baseAmount); allowances[fromAddr][msg.sender] = finalAmount; //----- emit Transfer(fromAddr, toAddr, amountInWei); return true; } //-------------------------------------------------------------------------- function approve(address spender, uint256 amountInWei) public returns (bool) { allowances[msg.sender][spender] = amountInWei; emit Approval(msg.sender, spender, amountInWei); return true; } //-------------------------------------------------------------------------- function() external { assert(true == false); // If Ether is sent to this address, don't handle it } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function transferOwnership(address newOwner) public onlyOwner // @param newOwner The address to transfer ownership to. { require(newOwner != address(0)); emit OnOwnershipTransfered(owner, newOwner); owner = newOwner; totalSoldByOwner = 0; } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function manageMazl(address walletTo, uint256 amountInWei) /*private*/ public returns(uint256) { uint256 addAmountInWei; uint256 baseAmount; uint256 finalAmount; uint256 mazlInWei; addAmountInWei = amountInWei; if (msg.sender!=admin && msg.sender!=owner) { mazlInWei = (amountInWei * mazl) / vScale; if (mazlInWei <= amountInWei) { addAmountInWei = amountInWei - mazlInWei; baseAmount = balances[mazler]; finalAmount = baseAmount + mazlInWei; if (finalAmount>=baseAmount) { balances[mazler] = finalAmount; emit Transfer(walletTo, mazler, mazlInWei); } } } return addAmountInWei; } //-------------------------------------------------------------------------- function changeAdminUser(address newAdminAddress) public onlyOwner returns(uint256) { require(newAdminAddress!=address(0x0)); emit OnAdminUserChanged(admin, newAdminAddress); admin = newAdminAddress; return 1; // for API use } //-------------------------------------------------------------------------- function changeMazlUser(address newAddress) public onlyOwner returns(uint256) { require(newAddress!=address(0x0)); emit OnVautingUserChanged(admin, newAddress); mazler = newAddress; return 1; // for API use } } //////////////////////////////////////////////////////////////////////////////// contract DiamondTransaction is ERC20 { struct TDiamondTransaction { bool isBuyTransaction; // Tells if this transaction was for us to buy diamonds or just to sell diamonds uint authorityId; // id(0)=GIA uint certificate; // Can be a direct certificat value (from GIA), or an HEX value if alpnumeric from other authorities uint providerId; // The vendor/Acqueror of the TTransaction uint vaultId; // ID of the secured vault used in our database uint sourceId; // Diamcoin: 0 partners > 0 uint caratAmount; // 3 decimals value flatten to an integer uint tokenAmount; // uint tokenId; // ID of the token used to sold. IT should be id=0 for Diamcoin uint timestamp; // When the transaction occurred bool isValid; // Should always be TRUE (=1) } mapping(uint256 => TDiamondTransaction) diamondTransactions; uint256[] diamondTransactionIds; event OnDiamondBoughTransaction ( uint256 authorityId, uint256 certificate, uint256 providerId, uint256 vaultId, uint256 caratAmount, uint256 tokenAmount, uint256 tokenId, uint256 timestamp ); event OnDiamondSoldTransaction ( uint256 authorityId, uint256 certificate, uint256 providerId, uint256 vaultId, uint256 caratAmount, uint256 tokenAmount, uint256 tokenId, uint256 timestamp ); //-------------------------------------------------------------------------- function storeDiamondTransaction(bool isBuy, uint256 indexInOurDb, uint256 authorityId, uint256 certificate, uint256 providerId, uint256 vaultId, uint256 caratAmount, uint256 tokenAmount, uint256 sourceId, uint256 tokenId) public onlyAdmin returns(bool) { TDiamondTransaction memory item; item.isBuyTransaction = isBuy; item.authorityId = authorityId; item.certificate = certificate; item.providerId = providerId; item.vaultId = vaultId; item.caratAmount = caratAmount; item.tokenAmount = tokenAmount; item.tokenId = tokenId; item.timestamp = now; item.isValid = true; item.sourceId = sourceId; diamondTransactions[indexInOurDb] = item; diamondTransactionIds.push(indexInOurDb)-1; if (isBuy) { emit OnDiamondBoughTransaction(authorityId, certificate, providerId, vaultId, caratAmount, tokenAmount, tokenId, now); } else { emit OnDiamondSoldTransaction( authorityId, certificate, providerId, vaultId, caratAmount, tokenAmount, tokenId, now); } return true; // this is only for our external API use } //-------------------------------------------------------------------------- function getDiamondTransaction(uint256 transactionId) public view returns(/*uint256,*/uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return ( (item.isBuyTransaction)?1:0, item.authorityId, item.certificate, item.providerId, item.vaultId, item.caratAmount, (item.isValid?1:0), item.tokenId, item.timestamp, item.sourceId ); } //-------------------------------------------------------------------------- function getEntitiesFromDiamondTransaction(uint256 transactionId) public view returns(uint256,uint256,uint256,uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return // If you want to know who was involved in that transaction ( item.authorityId, item.certificate, item.providerId, item.vaultId ); } //-------------------------------------------------------------------------- function getAmountsAndTypesFromDiamondTransaction(uint256 transactionId) public view returns(uint256,uint256,uint256,uint256,uint256,uint256,uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return ( (item.isBuyTransaction)?1:0, item.caratAmount, item.tokenAmount, item.tokenId, (item.isValid?1:0), item.timestamp, item.sourceId ); } //-------------------------------------------------------------------------- function getCaratAmountFromDiamondTransaction(uint256 transactionId) public view returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return item.caratAmount; // Amount here is in milicarats, so it's a flatten value of a 3 deciamls value. ie: 1.546 carats is 1546 here } //-------------------------------------------------------------------------- function getTokenAmountFromDiamondTransaction(uint256 transactionId) public view returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return item.tokenAmount; } //-------------------------------------------------------------------------- function isValidDiamondTransaction(uint256 transactionId) public view returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return (item.isValid?1:0); } //-------------------------------------------------------------------------- function changeDiamondTransactionStatus(uint256 transactionId, uint256 newStatus) public view onlyAdmin returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; item.isValid = (newStatus==0) ? false:false; // in case there was any issue with the transaction, set it as invalid (=2) or invalid=0 return 1; // needed for our API } //-------------------------------------------------------------------------- function getDiamondTransactionCount() public view returns(uint256) { return diamondTransactionIds.length; } //-------------------------------------------------------------------------- function getDiamondTransactionAtIndex(uint256 index) public view returns(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) { TDiamondTransaction memory DT; uint256 txId; if (index<diamondTransactionIds.length) { txId = diamondTransactionIds[index]; DT = diamondTransactions[txId]; return ( (DT.isBuyTransaction)?1:0, DT.authorityId, DT.certificate, DT.providerId, DT.vaultId, DT.caratAmount, (DT.isValid?1:0), DT.tokenId, DT.timestamp, DT.sourceId ); } return (0,0,0,0,0,0,0,0,0,0); } } //////////////////////////////////////////////////////////////////////////////// contract SocialLocker is DiamondTransaction { uint256 public minVotesCount = 20; bool public isSocialLockerEnabled = true; mapping(address => bool) voteLockedWallets; mapping(address => uint256) refundTotalVotes; mapping(address => uint256) unlockingTotalVotes; mapping(address => bool) forbiddenVoters; mapping(address => mapping(address => bool)) votersMap; // Used to avoid one voter to vote twice on the same user event OnLockedWallet( address lockedWallet, uint256 timestamp); event OnVotedForRefund( address voter, address walletToVoteFor, uint256 voteScore, uint256 maxVotes); // People has voted to refund all tokens from the involved wallet. it's a social voting event OnVotedForUnlocking(address voter, address walletToVoteFor, uint256 voteScore, uint256 maxVotes); // People has voted to unlock this wallet event OnVoterBannished( address voter); event OnVoterAllowed( address voter); event OnWalletBlocked( address wallet); // The wallet will no more be allowed to send nor receive tokens event OnSocialLockerWalletDepleted(address possibleFraudster); event OnSocialLockerWalletUnlocked(address possibleFraudster); event OnSocialLockerStateChanged(bool oldState, bool newState); event OnSocialLockerChangeMinVoteCount(uint oldMinVoteCount, uint newMinVoteCount); event OnWalletTaggedForSocialLocking(address taggedWallet); //-------------------------------------------------------------------------- function changeSocialLockerState(bool newState) public onlyAdmin returns(uint256) { emit OnSocialLockerStateChanged(isSocialLockerEnabled, newState); isSocialLockerEnabled = newState; return 1; } //-------------------------------------------------------------------------- function changeMinVoteCount(uint256 newMinVoteCount) public onlyAdmin returns(uint256) { emit OnSocialLockerChangeMinVoteCount(minVotesCount, newMinVoteCount); minVotesCount = newMinVoteCount; return 1; } //-------------------------------------------------------------------------- function tagWalletForVoting(address walletToTag) public onlyAdmin returns(uint256) { voteLockedWallets[walletToTag] = true; // now people can vote for a refund or to unlock this wallet unlockingTotalVotes[walletToTag] = 0; // no votes yet on this refundTotalVotes[walletToTag] = 0; // no vote yet emit OnWalletTaggedForSocialLocking(walletToTag); return 1; } //-------------------------------------------------------------------------- function voteForARefund(address voter, address possibleFraudster) public returns(uint256) { uint256 currentVoteCount; uint256 sum; uint256 baseAmount; uint256 finalAmount; require(voteLockedWallets[possibleFraudster] && !forbiddenVoters[voter] && !votersMap[possibleFraudster][voter] && isSocialLockerEnabled); // Don't vote on wallets not yet locked by ADMIN. To avoid abuse and security issues votersMap[possibleFraudster][voter] = true; // Ok, this voter just voted, don't allow anymore votes from him on the possibleFraudster currentVoteCount = refundTotalVotes[possibleFraudster]; sum = currentVoteCount + 1; assert(currentVoteCount<sum); refundTotalVotes[possibleFraudster] = sum; emit OnVotedForRefund(voter, possibleFraudster, sum, minVotesCount); // People has voted to refund all tokens from the involved wallet. it's a social voting //----- if (sum>=minVotesCount) // The VOTE is Finished!!! { baseAmount = balances[owner]; finalAmount = baseAmount + balances[possibleFraudster]; assert(finalAmount >= baseAmount); balances[owner] = finalAmount; // The official Token owner receives back the token (voted as to be refunded) balances[possibleFraudster] = 0; // Sorry scammer, but the vote said you won't have even 1 token in your wallet! voteLockedWallets[possibleFraudster] = false; emit Transfer(possibleFraudster, owner, balances[possibleFraudster]); } return 1; } //-------------------------------------------------------------------------- function voteForUnlocking(address voter, address possibleFraudster) public returns(uint256) { uint256 currentVoteCount; uint256 sum; require(voteLockedWallets[possibleFraudster] && !forbiddenVoters[voter] && !votersMap[possibleFraudster][voter] && isSocialLockerEnabled); // Don't vote on wallets not yet locked by ADMIN. To avoid abuse and security issues votersMap[possibleFraudster][voter] = true; // don't let the voter votes again for this possibleFraudster currentVoteCount = unlockingTotalVotes[possibleFraudster]; sum = currentVoteCount + 1; assert(currentVoteCount<sum); unlockingTotalVotes[possibleFraudster] = sum; emit OnVotedForUnlocking(voter, possibleFraudster, sum, minVotesCount); // People has voted to refund all tokens from the involved wallet. it's a social voting //----- if (sum>=minVotesCount) // The VOTE is Finished!!! { voteLockedWallets[possibleFraudster] = false; // Redemption allowed by the crowd } return 1; } //-------------------------------------------------------------------------- function banVoter(address voter) public onlyAdmin returns(uint256) { forbiddenVoters[voter] = true; // this user cannot vote anymore. A possible abuser emit OnVoterBannished(voter); } //-------------------------------------------------------------------------- function allowVoter(address voter) public onlyAdmin returns(uint256) { forbiddenVoters[voter] = false; // this user cannot vote anymore. A possible abuser emit OnVoterAllowed(voter); } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- } //////////////////////////////////////////////////////////////////////////////// contract Token is SocialLocker { address public validator; // Address of the guy who will validate any extend/reduce query. so it's considered as Admin2 here. Adm uint256 public minDelayBeforeStockChange = 6*3600; // StockReduce allowed EVERY 6 hours only uint256 public maxReduceInUnit = 5000000; uint256 public maxReduce = maxReduceInUnit * 10**decimals; // Don't allow a supply decrease if above this amount' uint256 public maxExtendInUnit = maxReduceInUnit; uint256 public maxExtend = maxExtendInUnit * 10**decimals; // Don't allow a supply decrease if above this amount' uint256 constant decimalMultiplicator = 10**decimals; uint256 lastReduceCallTime = 0; bool public isReduceStockValidated = false; /// A validator (=2nd admin) needs to confitm the action before changing the stock quantity bool public isExtendStockValidated = false; /// same... uint256 public reduceVolumeInUnit = 0; /// Used when asking to reduce amount of token. validator needs to confirm first! uint256 public extendVolumeInUnit = 0; /// Used when asking to extend amount of token. validator needs to confirm first! //----- modifier onlyValidator() { require(msg.sender==validator); _; } //----- event OnStockVolumeExtended(uint256 volumeInUnit, uint256 volumeInDecimal, uint256 newTotalSupply); event OnStockVolumeReduced( uint256 volumeInUnit, uint256 volumeInDecimal, uint256 newTotalSupply); event OnErrorLog(string functionName, string errorMsg); event OnLogNumber(string section, uint256 value); event OnMaxReduceChanged(uint256 maxReduceInUnit, uint256 oldQuantity); event OnMaxExtendChanged(uint256 maxExtendInUnit, uint256 oldQuantity); event OnValidationUserChanged(address oldValidator, address newValidator); //-------------------------------------------------------------------------- constructor() public { validator = owner; } //-------------------------------------------------------------------------- function changeMaxReduceQuantity(uint256 newQuantityInUnit) public onlyAdmin returns(uint256) { uint256 oldQuantity = maxReduceInUnit; maxReduceInUnit = newQuantityInUnit; maxReduce = maxReduceInUnit * 10**decimals; emit OnMaxReduceChanged(maxReduceInUnit, oldQuantity); return 1; // used for the API (outside the smartcontract) } //-------------------------------------------------------------------------- function changeMaxExtendQuantity(uint256 newQuantityInUnit) public onlyAdmin returns(uint256) { uint256 oldQuantity = maxExtendInUnit; maxExtendInUnit = newQuantityInUnit; maxExtend = maxExtendInUnit * 10**decimals; emit OnMaxExtendChanged(maxExtendInUnit, oldQuantity); return 1; // used for the API (outside the smartcontract) } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function changeValidationUser(address newValidatorAddress) public onlyOwner returns(uint256) // The validation user is the guy who will finally confirm a token reduce or a token extend { require(newValidatorAddress!=address(0x0)); emit OnValidationUserChanged(validator, newValidatorAddress); validator = newValidatorAddress; return 1; } //-------------------------------------------------------------------------- function changeMinDelayBeforeStockChange(uint256 newDelayInSecond) public onlyAdmin returns(uint256) { if (newDelayInSecond<60) return 0; // not less than one minute else if (newDelayInSecond>24*3600) return 0; // not more than 24H of waiting minDelayBeforeStockChange = newDelayInSecond; emit OnLogNumber("changeMinDelayBeforeReduce", newDelayInSecond); return 1; // for API use } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function requestExtendStock(uint256 volumeInUnit) public onlyAdmin returns(uint256) { require(volumeInUnit<=maxExtendInUnit); isExtendStockValidated = true; extendVolumeInUnit = volumeInUnit; // If a request was already done, the volume will be changed with this one return 1; // for API use } //-------------------------------------------------------------------------- function cancelExtendStock() public onlyValidator returns(uint256) { isExtendStockValidated = false; // Cancel any request posted by admin return 1; // for API use } //-------------------------------------------------------------------------- function extendStock(uint256 volumeAllowedInUnit) public onlyValidator returns(uint256,uint256,uint256,uint256) { if (!isExtendStockValidated) // Validator (admin2) must validate the query first! { emit OnErrorLog("extendStock", "Request not validated yet"); return (0,0,0,0); } require(extendVolumeInUnit<=maxExtendInUnit); require(volumeAllowedInUnit==extendVolumeInUnit); // Don't allow the admin set arbritrary volume before validation //----- uint256 extraVolumeInDecimal = extendVolumeInUnit * decimalMultiplicator; // value in WEI //----- totalSupply = totalSupply.add(extraVolumeInDecimal); uint256 baseAmount = totalSupply; uint256 finalAmount = baseAmount + extraVolumeInDecimal; assert(finalAmount >= baseAmount); totalSupply = finalAmount; //----- balances[owner] = balances[owner].add(extraVolumeInDecimal); baseAmount = balances[owner]; finalAmount = baseAmount + extraVolumeInDecimal; assert(finalAmount >= baseAmount); balances[owner] = finalAmount; //----- isExtendStockValidated = false; // reset for the next extend request emit OnStockVolumeExtended(extendVolumeInUnit, extraVolumeInDecimal, totalSupply); return ( extendVolumeInUnit, extraVolumeInDecimal, balances[owner], totalSupply ); // origin:0 OWNER origin:1 AN_EXCHANGE } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function requestReduceStock(uint256 volumeInUnit) public onlyAdmin returns(uint256) { require(volumeInUnit<=maxReduceInUnit); isReduceStockValidated = true; reduceVolumeInUnit = volumeInUnit; // If a request was already done, the volume will be changed with this one return 1; // for API use } //-------------------------------------------------------------------------- function cancelReduceStock() public onlyValidator returns(uint256) { isReduceStockValidated = false; // Cancel any request posted by admin return 1; // for API use } //-------------------------------------------------------------------------- function reduceStock(uint256 volumeAllowedInUnit) public onlyValidator returns(uint256,uint256,uint256,uint256) { if (!isReduceStockValidated) // Validator (admin2) must validate the query first! { emit OnErrorLog("reduceStock", "Request not validated yet"); return (0,0,0,0); } require(reduceVolumeInUnit<=maxReduceInUnit); require(volumeAllowedInUnit==reduceVolumeInUnit); // Don't allow the admin set arbritrary volume before validation if (!isReduceAllowedNow()) { return (0,0,0,0); } lastReduceCallTime = now; //----- uint256 reducedVolumeInDecimal = reduceVolumeInUnit * decimalMultiplicator; // value in WEI //----- totalSupply = totalSupply.sub(reducedVolumeInDecimal); uint256 baseAmount = totalSupply; uint256 finalAmount = baseAmount - reducedVolumeInDecimal; assert(finalAmount <= baseAmount); totalSupply = finalAmount; //----- balances[owner] = balances[owner].sub(reducedVolumeInDecimal); baseAmount = balances[owner]; finalAmount = baseAmount - reducedVolumeInDecimal; assert(finalAmount <= baseAmount); balances[owner] = finalAmount; //----- emit OnStockVolumeReduced(reduceVolumeInUnit, reducedVolumeInDecimal, totalSupply); return ( reduceVolumeInUnit, reducedVolumeInDecimal, balances[owner], totalSupply ); } //-------------------------------------------------------------------------- function isReduceAllowedNow() public view returns(bool) { uint256 delay = now - lastReduceCallTime; return (delay >= minDelayBeforeStockChange); } //-------------------------------------------------------------------------- function getStockBalance() public view returns(uint256) { return totalSupply; } }
--------------------------------------------------------------------------
function getTokenAmountFromDiamondTransaction(uint256 transactionId) public view returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return item.tokenAmount; }
7,318,506
./full_match/5/0x951248c00804803C9bD3AD780728ea395d0A960C/sources/contracts/DrugSupplyChain.sol
Function to get the manufacturer address of a drug using its ID
function getDrugManufacturerAddress(uint _id) public view returns (address) { return drugs[_id].manufacturerAddress; }
11,611,709