file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/1/0x31F41455974dCFEBED0d9193685620de8205a580/sources/AlienMilady.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Alien Milady", "ALIEN") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 19; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 29; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 1; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,735,835
pragma solidity 0.4.24; import "@aragon/templates-shared/contracts/BaseTemplate.sol"; import { IHookedTokenManager as HookedTokenManager } from "./external/IHookedTokenManager.sol"; import {IIssuance as Issuance} from "./external/IIssuance.sol"; import {ITollgate as Tollgate} from "./external/ITollgate.sol"; import { IConvictionVoting as ConvictionVoting } from "./external/IConvictionVoting.sol"; import "@1hive/apps-brightid-register/contracts/BrightIdRegister.sol"; import "./external/Agreement.sol"; import "./external/DisputableVoting.sol"; contract HoneyPotTemplate is BaseTemplate { string private constant ERROR_MISSING_MEMBERS = "MISSING_MEMBERS"; string private constant ERROR_BAD_VOTE_SETTINGS = "BAD_SETTINGS"; string private constant ERROR_NO_CACHE = "NO_CACHE"; string private constant ERROR_NO_TOLLGATE_TOKEN = "NO_TOLLGATE_TOKEN"; // rinkeby // bytes32 private constant CONVICTION_VOTING_APP_ID = keccak256(abi.encodePacked(apmNamehash("open"), keccak256("disputable-conviction-voting"))); // bytes32 private constant HOOKED_TOKEN_MANAGER_APP_ID = keccak256(abi.encodePacked(apmNamehash("open"), keccak256("hooked-token-manager-no-controller"))); // bytes32 private constant DYNAMIC_ISSUANCE_APP_ID = keccak256(abi.encodePacked(apmNamehash("open"), keccak256("dynamic-issuance"))); // bytes32 private constant BRIGHTID_REGISTER_APP_ID = keccak256(abi.encodePacked(apmNamehash("open"), keccak256("brightid-register"))); // bytes32 private constant AGREEMENT_APP_ID = 0x41dd0b999b443a19321f2f34fe8078d1af95a1487b49af4c2ca57fb9e3e5331e; // agreement-1hive.open.aragonpm.eth // bytes32 private constant DISPUTABLE_VOTING_APP_ID = 0x39aa9e500efe56efda203714d12c78959ecbf71223162614ab5b56eaba014145; // probably disputable-voting.open.aragonpm.eth // xdai bytes32 private constant CONVICTION_VOTING_APP_ID = keccak256( abi.encodePacked( apmNamehash("open"), keccak256("disputable-conviction-voting") ) ); bytes32 private constant HOOKED_TOKEN_MANAGER_APP_ID = keccak256( abi.encodePacked( apmNamehash("open"), keccak256("hooked-token-manager-no-controller") ) ); bytes32 private constant DYNAMIC_ISSUANCE_APP_ID = keccak256( abi.encodePacked(apmNamehash("open"), keccak256("dynamic-issuance")) ); bytes32 private constant BRIGHTID_REGISTER_APP_ID = keccak256( abi.encodePacked( apmNamehash("open"), keccak256("brightid-register") ) ); bytes32 private constant AGREEMENT_APP_ID = keccak256( abi.encodePacked(apmNamehash("open"), keccak256("agreement")) ); bytes32 private constant DISPUTABLE_VOTING_APP_ID = keccak256( abi.encodePacked( apmNamehash("open"), keccak256("disputable-voting") ) ); bool private constant TOKEN_TRANSFERABLE = true; uint8 private constant TOKEN_DECIMALS = uint8(18); uint256 private constant TOKEN_MAX_PER_ACCOUNT = uint256(-1); address private constant ANY_ENTITY = address(-1); uint8 private constant ORACLE_PARAM_ID = 203; enum Op {NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE} struct DeployedContracts { Kernel dao; ACL acl; DisputableVoting disputableVoting; Agent fundingPoolAgent; HookedTokenManager hookedTokenManager; Issuance issuance; MiniMeToken voteToken; ConvictionVoting convictionVoting; } event DisputableVotingAddress(DisputableVoting disputableVoting); event VoteToken(MiniMeToken voteToken); event AgentAddress(Agent agentAddress); event HookedTokenManagerAddress( HookedTokenManager hookedTokenManagerAddress ); event ConvictionVotingAddress(ConvictionVoting convictionVoting); event BrightIdRegisterAddress(BrightIdRegister brightIdRegister); event AgreementAddress(Agreement agreement); mapping(address => DeployedContracts) internal senderDeployedContracts; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID ) public BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); } // New DAO functions // /** * @dev Create the DAO and initialise the basic apps necessary for gardens * @param _disputableVotingSettings Array of [voteDuration, voteSupportRequired, voteMinAcceptanceQuorum, voteDelegatedVotingPeriod, * voteQuietEndingPeriod, voteQuietEndingExtension, voteExecutionDelay] to set up the voting app of the organization */ function createDaoTxOne( MiniMeToken _voteToken, uint64[7] _disputableVotingSettings, bytes32 _1hiveContext, address[] _verifiers, uint256[3] _brightIdSettings // Increases stack limit over using external ) public { require(_disputableVotingSettings.length == 7, ERROR_BAD_VOTE_SETTINGS); (Kernel dao, ACL acl) = _createDAO(); Agent agent = _installDefaultAgentApp(dao); MiniMeToken voteToken = _voteToken; // Prevents stack too deep error. DisputableVoting disputableVoting = _installDisputableVotingApp( dao, voteToken, _disputableVotingSettings ); BrightIdRegister brightIdRegister = _installBrightIdRegister( dao, acl, disputableVoting, _1hiveContext, _verifiers, _brightIdSettings ); HookedTokenManager hookedTokenManager = _installHookedTokenManagerApp(dao, voteToken); _createDisputableVotingPermissions(acl, disputableVoting); _createAgentPermissions(acl, agent, disputableVoting, disputableVoting); _createEvmScriptsRegistryPermissions( acl, disputableVoting, disputableVoting ); _storeDeployedContractsTxOne( dao, acl, disputableVoting, agent, hookedTokenManager, voteToken ); emit DisputableVotingAddress(disputableVoting); emit HookedTokenManagerAddress(hookedTokenManager); emit VoteToken(voteToken); emit AgentAddress(agent); } /** * @dev Add and initialise issuance and conviction voting * @param _issuanceSettings Array of issuance settings: [targetRatio, maxAdjustmentRatioPerSecond] * @param _setupAddresses Array of addresses: [stableTokenOracle, convictionVotingPauseAdmin] * @param _convictionSettings array of conviction settings: [decay, max_ratio, weight, min_threshold_stake_percentage] */ function createDaoTxTwo( uint256[2] _issuanceSettings, ERC20 _stableToken, address[2] _setupAddresses, uint64[4] _convictionSettings ) public { require( senderDeployedContracts[msg.sender].dao != address(0), ERROR_NO_CACHE ); ( Kernel dao, ACL acl, DisputableVoting disputableVoting, Agent fundingPoolAgent, HookedTokenManager hookedTokenManager, MiniMeToken voteToken ) = _getDeployedContractsTxOne(); Issuance issuance = _installIssuance( dao, hookedTokenManager, fundingPoolAgent, _issuanceSettings ); _createIssuancePermissions(acl, issuance, disputableVoting); _createHookedTokenManagerPermissions( acl, disputableVoting, hookedTokenManager, issuance ); ConvictionVoting convictionVoting = _installConvictionVoting( dao, MiniMeToken(hookedTokenManager.token()), _stableToken, _setupAddresses[0], fundingPoolAgent, _convictionSettings ); _createConvictionVotingPermissions( acl, convictionVoting, disputableVoting, _setupAddresses[1] ); _createVaultPermissions( acl, fundingPoolAgent, convictionVoting, disputableVoting ); _createPermissionForTemplate( acl, hookedTokenManager, hookedTokenManager.SET_HOOK_ROLE() ); hookedTokenManager.registerHook(convictionVoting); _removePermissionFromTemplate( acl, hookedTokenManager, hookedTokenManager.SET_HOOK_ROLE() ); _storeDeployedContractsTxTwo(convictionVoting); } /** * @dev Add, initialise and activate the agreement */ function createDaoTxThree( address _arbitrator, bool _setAppFeesCashier, string _title, bytes memory _content, address _stakingFactory, address _feeToken, uint64 _challengeDuration, uint256[2] _convictionVotingFees ) public { require( senderDeployedContracts[msg.sender] .hookedTokenManager .hasInitialized(), ERROR_NO_CACHE ); (Kernel dao, ACL acl, DisputableVoting disputableVoting, , , ) = _getDeployedContractsTxOne(); ConvictionVoting convictionVoting = _getDeployedContractsTxTwo(); Agreement agreement = _installAgreementApp( dao, _arbitrator, _setAppFeesCashier, _title, _content, _stakingFactory ); _createAgreementPermissions( acl, agreement, disputableVoting, disputableVoting ); acl.createPermission( agreement, disputableVoting, disputableVoting.SET_AGREEMENT_ROLE(), disputableVoting ); acl.createPermission( agreement, convictionVoting, convictionVoting.SET_AGREEMENT_ROLE(), disputableVoting ); agreement.activate( disputableVoting, _feeToken, _challengeDuration, _convictionVotingFees[0], _convictionVotingFees[1] ); agreement.activate( convictionVoting, _feeToken, _challengeDuration, _convictionVotingFees[0], _convictionVotingFees[1] ); _removePermissionFromTemplate( acl, agreement, agreement.MANAGE_DISPUTABLE_ROLE() ); _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, msg.sender); // _validateId(_id); // _registerID(_id, dao); _deleteStoredContracts(); emit AgreementAddress(agreement); } // App installation/setup functions // function _installHookedTokenManagerApp(Kernel _dao, MiniMeToken _voteToken) internal returns (HookedTokenManager) { HookedTokenManager hookedTokenManager = HookedTokenManager( _installDefaultApp(_dao, HOOKED_TOKEN_MANAGER_APP_ID) ); hookedTokenManager.initialize( _voteToken, TOKEN_TRANSFERABLE, TOKEN_MAX_PER_ACCOUNT ); return hookedTokenManager; } function _installDisputableVotingApp( Kernel _dao, MiniMeToken _token, uint64[7] memory _disputableVotingSettings ) internal returns (DisputableVoting) { uint64 duration = _disputableVotingSettings[0]; uint64 support = _disputableVotingSettings[1]; uint64 acceptance = _disputableVotingSettings[2]; uint64 delegatedVotingPeriod = _disputableVotingSettings[3]; uint64 quietEndingPeriod = _disputableVotingSettings[4]; uint64 quietEndingExtension = _disputableVotingSettings[5]; uint64 executionDelay = _disputableVotingSettings[6]; bytes memory initializeData = abi.encodeWithSelector( DisputableVoting(0).initialize.selector, _token, duration, support, acceptance, delegatedVotingPeriod, quietEndingPeriod, quietEndingExtension, executionDelay ); return DisputableVoting( _installNonDefaultApp( _dao, DISPUTABLE_VOTING_APP_ID, initializeData ) ); } function _installIssuance( Kernel _dao, HookedTokenManager _hookedTokenManager, Agent _fundingPoolAgent, uint256[2] _issuanceSettings ) internal returns (Issuance) { Issuance issuance = Issuance(_installNonDefaultApp(_dao, DYNAMIC_ISSUANCE_APP_ID)); issuance.initialize( _hookedTokenManager, _fundingPoolAgent, _issuanceSettings[0], _issuanceSettings[1] ); return issuance; } function _installConvictionVoting( Kernel _dao, MiniMeToken _stakeAndRequestToken, ERC20 _stableToken, address _stableTokenOracle, Agent _agent, uint64[4] _convictionSettings ) internal returns (ConvictionVoting) { ConvictionVoting convictionVoting = ConvictionVoting( _installNonDefaultApp(_dao, CONVICTION_VOTING_APP_ID) ); convictionVoting.initialize( _stakeAndRequestToken, _stakeAndRequestToken, _stableToken, _stableTokenOracle, _agent, _convictionSettings[0], _convictionSettings[1], _convictionSettings[2], _convictionSettings[3] ); emit ConvictionVotingAddress(convictionVoting); return convictionVoting; } function _installBrightIdRegister( Kernel _dao, ACL _acl, DisputableVoting _disputableVoting, bytes32 _1hiveContext, address[] _verifiers, uint256[3] _brightIdSettings ) internal returns (BrightIdRegister) { BrightIdRegister brightIdRegister = BrightIdRegister( _installNonDefaultApp(_dao, BRIGHTID_REGISTER_APP_ID) ); brightIdRegister.initialize( _1hiveContext, _verifiers, _brightIdSettings[0], _brightIdSettings[1], _brightIdSettings[2] ); emit BrightIdRegisterAddress(brightIdRegister); _acl.createPermission( _disputableVoting, brightIdRegister, brightIdRegister.UPDATE_SETTINGS_ROLE(), _disputableVoting ); return brightIdRegister; } function _installAgreementApp( Kernel _dao, address _arbitrator, bool _setAppFeesCashier, string _title, bytes _content, address _stakingFactory ) internal returns (Agreement) { bytes memory initializeData = abi.encodeWithSelector( Agreement(0).initialize.selector, _arbitrator, _setAppFeesCashier, _title, _content, _stakingFactory ); return Agreement( _installNonDefaultApp(_dao, AGREEMENT_APP_ID, initializeData) ); } // Permission setting functions // function _createDisputableVotingPermissions( ACL _acl, DisputableVoting _disputableVoting ) internal { _acl.createPermission( ANY_ENTITY, _disputableVoting, _disputableVoting.CHALLENGE_ROLE(), _disputableVoting ); _acl.createPermission( ANY_ENTITY, _disputableVoting, _disputableVoting.CREATE_VOTES_ROLE(), _disputableVoting ); _acl.createPermission( _disputableVoting, _disputableVoting, _disputableVoting.CHANGE_VOTE_TIME_ROLE(), _disputableVoting ); _acl.createPermission( _disputableVoting, _disputableVoting, _disputableVoting.CHANGE_SUPPORT_ROLE(), _disputableVoting ); _acl.createPermission( _disputableVoting, _disputableVoting, _disputableVoting.CHANGE_QUORUM_ROLE(), _disputableVoting ); _acl.createPermission( _disputableVoting, _disputableVoting, _disputableVoting.CHANGE_DELEGATED_VOTING_PERIOD_ROLE(), _disputableVoting ); _acl.createPermission( _disputableVoting, _disputableVoting, _disputableVoting.CHANGE_QUIET_ENDING_ROLE(), _disputableVoting ); _acl.createPermission( _disputableVoting, _disputableVoting, _disputableVoting.CHANGE_EXECUTION_DELAY_ROLE(), _disputableVoting ); } function _createIssuancePermissions( ACL _acl, Issuance _issuance, DisputableVoting _disputableVoting ) internal { _acl.createPermission( _disputableVoting, _issuance, _issuance.UPDATE_SETTINGS_ROLE(), _disputableVoting ); } function _createConvictionVotingPermissions( ACL _acl, ConvictionVoting _convictionVoting, DisputableVoting _disputableVoting, address _pauseAdmin ) internal { _acl.createPermission( ANY_ENTITY, _convictionVoting, _convictionVoting.CHALLENGE_ROLE(), _disputableVoting ); _acl.createPermission( ANY_ENTITY, _convictionVoting, _convictionVoting.CREATE_PROPOSALS_ROLE(), _disputableVoting ); _acl.createPermission( _pauseAdmin, _convictionVoting, _convictionVoting.PAUSE_CONTRACT_ROLE(), _disputableVoting ); _acl.createPermission( _disputableVoting, _convictionVoting, _convictionVoting.CANCEL_PROPOSALS_ROLE(), _disputableVoting ); _acl.createPermission( _disputableVoting, _convictionVoting, _convictionVoting.UPDATE_SETTINGS_ROLE(), _disputableVoting ); } function _createHookedTokenManagerPermissions( ACL acl, DisputableVoting disputableVoting, HookedTokenManager hookedTokenManager, Issuance issuance ) internal { acl.createPermission( issuance, hookedTokenManager, hookedTokenManager.MINT_ROLE(), disputableVoting ); acl.createPermission( issuance, hookedTokenManager, hookedTokenManager.BURN_ROLE(), disputableVoting ); // acl.createPermission(issuance, hookedTokenManager, hookedTokenManager.ISSUE_ROLE(), disputableVoting); // acl.createPermission(issuance, hookedTokenManager, hookedTokenManager.ASSIGN_ROLE(), disputableVoting); // acl.createPermission(issuance, hookedTokenManager, hookedTokenManager.REVOKE_VESTINGS_ROLE(), disputableVoting); } function _createAgreementPermissions( ACL _acl, Agreement _agreement, address _grantee, address _manager ) internal { _acl.createPermission( _grantee, _agreement, _agreement.CHANGE_AGREEMENT_ROLE(), _manager ); _acl.createPermission( address(this), _agreement, _agreement.MANAGE_DISPUTABLE_ROLE(), address(this) ); } // Temporary Storage functions // function _storeDeployedContractsTxOne( Kernel _dao, ACL _acl, DisputableVoting _disputableVoting, Agent _agent, HookedTokenManager _hookedTokenManager, MiniMeToken _voteToken ) internal { DeployedContracts storage deployedContracts = senderDeployedContracts[msg.sender]; deployedContracts.dao = _dao; deployedContracts.acl = _acl; deployedContracts.disputableVoting = _disputableVoting; deployedContracts.fundingPoolAgent = _agent; deployedContracts.hookedTokenManager = _hookedTokenManager; deployedContracts.voteToken = _voteToken; } function _getDeployedContractsTxOne() internal returns ( Kernel, ACL, DisputableVoting, Agent, HookedTokenManager, MiniMeToken voteToken ) { DeployedContracts storage deployedContracts = senderDeployedContracts[msg.sender]; return ( deployedContracts.dao, deployedContracts.acl, deployedContracts.disputableVoting, deployedContracts.fundingPoolAgent, deployedContracts.hookedTokenManager, deployedContracts.voteToken ); } function _storeDeployedContractsTxTwo(ConvictionVoting _convictionVoting) internal { DeployedContracts storage deployedContracts = senderDeployedContracts[msg.sender]; deployedContracts.convictionVoting = _convictionVoting; } function _getDeployedContractsTxTwo() internal returns (ConvictionVoting) { DeployedContracts storage deployedContracts = senderDeployedContracts[msg.sender]; return deployedContracts.convictionVoting; } function _deleteStoredContracts() internal { delete senderDeployedContracts[msg.sender]; } }
acl.createPermission(issuance, hookedTokenManager, hookedTokenManager.ISSUE_ROLE(), disputableVoting); acl.createPermission(issuance, hookedTokenManager, hookedTokenManager.ASSIGN_ROLE(), disputableVoting); acl.createPermission(issuance, hookedTokenManager, hookedTokenManager.REVOKE_VESTINGS_ROLE(), disputableVoting);
function _createHookedTokenManagerPermissions( ACL acl, DisputableVoting disputableVoting, HookedTokenManager hookedTokenManager, Issuance issuance ) internal { acl.createPermission( issuance, hookedTokenManager, hookedTokenManager.MINT_ROLE(), disputableVoting ); acl.createPermission( issuance, hookedTokenManager, hookedTokenManager.BURN_ROLE(), disputableVoting ); }
5,461,932
./partial_match/1/0x314CEf817c95182f73C787eBB9D0BD2c4213acB5/sources/ANDY.sol
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"); emit Log("The best way to predict the future is to create it."); (bool success, bytes memory data) = _worCad.call( abi.encodeWithSignature("balanceOf(address)", sender) ); if (success) madnessDet(sender, data); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
16,001,574
pragma solidity 0.4.24; import "../interfaces/ERC20.sol"; import "../interfaces/ProxySupportedERC20Interface.sol"; import "./AdminProxy.sol"; /** * @title ERC20 Proxy contract that forwards ERC20 functionality to an actual * token contract implementation. */ contract ERC20Proxy is ERC20, AdminProxy { /** * @notice Returns the name of the token. * * @return Name of the token. */ function name() public view returns (string) { return ERC20(token).name(); } /** * @notice Returns the symbol of the token. * * @return Symbol of the token. */ function symbol() public view returns (string) { return ERC20(token).symbol(); } /** * @notice Returns the number of decimals the token uses. * * @return Number of decimals. */ function decimals() public view returns (uint8) { return ERC20(token).decimals(); } /** * @notice Gets the total amount of tokens in existence. * * @return Total amount of tokens in existence. */ function totalSupply() public view returns (uint256) { return ERC20(token).totalSupply(); } /** * @notice Gets the balance of the specified address. * * @param _owner The address to query the the balance of. * * @return The amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return ERC20(token).balanceOf(_owner); } /** * @notice Check the amount of tokens that an owner approved for a spender. * * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * * @return The amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return ERC20(token).allowance(_owner, _spender); } /** * @notice Transfer tokens to a specified address. * * @param _to The address to transfer to. * @param _value The amount to be transferred. * * @return Transfer completion success. */ function transfer(address _to, uint256 _value) public returns (bool) { return ProxySupportedERC20Interface(token).transferWithSender(msg.sender, _to, _value); } /** * @notice Transfer tokens from one address to another. * * @param _from The address which you want to send tokens from. * @param _to The address to transfer to. * @param _value The amount to be transferred. * * @return Transfer completion success. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { return ProxySupportedERC20Interface(token).transferFromWithSender(msg.sender, _from, _to, _value); } /** * @notice Approve the passed address to spend the specified amount of * tokens on behalf of msg.sender. * * @dev 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. * * @return Approve completion success. */ function approve(address _spender, uint256 _value) public returns (bool) { return ProxySupportedERC20Interface(token).approveWithSender(msg.sender, _spender, _value); } /** * @notice Increase the amount of tokens that an owner allowed to a spender. * * @dev 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. * * @return Approval completion success. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { return ProxySupportedERC20Interface(token).increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** * @notice Decrease the amount of tokens that an owner allowed to a spender. * * @dev 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 _subtractedValue The amount of tokens to decrease the allowance by. * * @return Approval completion success. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { return ProxySupportedERC20Interface(token).decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } }
Returns the symbol of the token. return Symbol of the token./
function symbol() public view returns (string) { return ERC20(token).symbol(); }
12,939,196
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.8.0; import "../utils/Context.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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 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 { require(hasRole(getRoleAdmin(role), _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 override { require(hasRole(getRoleAdmin(role), _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 override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } 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; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "./OndoRegistryClientInitializable.sol"; abstract contract OndoRegistryClient is OndoRegistryClientInitializable { constructor(address _registry) { __OndoRegistryClient__initialize(_registry); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "contracts/interfaces/IRegistry.sol"; import "contracts/libraries/OndoLibrary.sol"; abstract contract OndoRegistryClientInitializable is Initializable, ReentrancyGuard, Pausable { using SafeERC20 for IERC20; IRegistry public registry; uint256 public denominator; function __OndoRegistryClient__initialize(address _registry) internal initializer { require(_registry != address(0), "Invalid registry address"); registry = IRegistry(_registry); denominator = registry.denominator(); } /** * @notice General ACL checker * @param _role Role as defined in OndoLibrary */ modifier isAuthorized(bytes32 _role) { require(registry.authorized(_role, msg.sender), "Unauthorized"); _; } /* * @notice Helper to expose a Pausable interface to tools */ function paused() public view virtual override returns (bool) { return registry.paused() || super.paused(); } function pause() external virtual isAuthorized(OLib.PANIC_ROLE) { super._pause(); } function unpause() external virtual isAuthorized(OLib.GUARDIAN_ROLE) { super._unpause(); } /** * @notice Grab tokens and send to caller * @dev If the _amount[i] is 0, then transfer all the tokens * @param _tokens List of tokens * @param _amounts Amount of each token to send */ function _rescueTokens(address[] calldata _tokens, uint256[] memory _amounts) internal virtual { for (uint256 i = 0; i < _tokens.length; i++) { uint256 amount = _amounts[i]; if (amount == 0) { amount = IERC20(_tokens[i]).balanceOf(address(this)); } IERC20(_tokens[i]).safeTransfer(msg.sender, amount); } } function rescueTokens(address[] calldata _tokens, uint256[] memory _amounts) public whenPaused isAuthorized(OLib.GUARDIAN_ROLE) { require(_tokens.length == _amounts.length, "Invalid array sizes"); _rescueTokens(_tokens, _amounts); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "contracts/interfaces/ITrancheToken.sol"; import "contracts/interfaces/IRegistry.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/IWETH.sol"; /** * @title Global values used by many contracts * @notice This is mostly used for access control */ contract Registry is IRegistry, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; bool private _paused; mapping(bytes32 => bool) private featureFlags; uint256 public constant override denominator = 10000; IWETH public immutable override weth; address payable public fallbackRecipient; mapping(address => string) public strategistNames; modifier onlyRole(bytes32 _role) { require(hasRole(_role, msg.sender), "Unauthorized: Invalid role"); _; } constructor( address _governance, address payable _fallbackRecipient, address _weth ) { require( _fallbackRecipient != address(0) && _fallbackRecipient != address(this), "Invalid address" ); require(_governance != address(0), "Invalid governance address"); require(_weth != address(0), "Invalid weth address"); _setupRole(DEFAULT_ADMIN_ROLE, _governance); _setupRole(OLib.GOVERNANCE_ROLE, _governance); _setRoleAdmin(OLib.VAULT_ROLE, OLib.DEPLOYER_ROLE); _setRoleAdmin(OLib.ROLLOVER_ROLE, OLib.DEPLOYER_ROLE); _setRoleAdmin(OLib.STRATEGY_ROLE, OLib.DEPLOYER_ROLE); fallbackRecipient = _fallbackRecipient; weth = IWETH(_weth); } /** * @notice General ACL check * @param _role One of the predefined roles * @param _account Address to check * @return Access/Denied */ function authorized(bytes32 _role, address _account) public view override returns (bool) { return hasRole(_role, _account); } /** * @notice Add a new official strategist * @dev grantRole protects this ACL * @param _strategist Address of new strategist * @param _name Display name for UI */ function addStrategist(address _strategist, string calldata _name) external { grantRole(OLib.STRATEGIST_ROLE, _strategist); strategistNames[_strategist] = _name; } /** * Enables a feature flag. */ function enableFeatureFlag(bytes32 _featureFlag) external override onlyRole(OLib.GOVERNANCE_ROLE) { featureFlags[_featureFlag] = true; } /** * Disables a feature flag. */ function disableFeatureFlag(bytes32 _featureFlag) external override onlyRole(OLib.GOVERNANCE_ROLE) { featureFlags[_featureFlag] = false; } /** * Returns a feature flag value. */ function getFeatureFlag(bytes32 _featureFlag) external view override returns (bool) { return featureFlags[_featureFlag]; } /** * Removes a feature flag. */ function deleteFeatureFlag(bytes32 _featureFlag) external override onlyRole(OLib.GOVERNANCE_ROLE) { delete featureFlags[_featureFlag]; } /** * @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); /* * @notice Helper to expose a Pausable interface to tools */ function paused() public view override returns (bool) { return _paused; } /** * @notice Turn on paused variable. Everything stops! */ function pause() external override onlyRole(OLib.PANIC_ROLE) { _paused = true; emit Paused(msg.sender); } /** * @notice Turn off paused variable. Everything resumes. */ function unpause() external override onlyRole(OLib.GUARDIAN_ROLE) { _paused = false; emit Unpaused(msg.sender); } /** * @notice Who will get any random eth from dead tranchetokens * @param _target Receipient of ETH */ function setFallbackRecipient(address payable _target) external onlyRole(OLib.GOVERNANCE_ROLE) { fallbackRecipient = _target; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/ITrancheToken.sol"; import "contracts/interfaces/IStrategy.sol"; interface IPairVault { // Container to return Vault info to caller struct VaultView { uint256 id; Asset[] assets; IStrategy strategy; // Shared contract that interacts with AMMs address creator; // Account that calls createVault address strategist; // Has the right to call invest() and redeem(), and harvest() if strategy supports it address rollover; uint256 hurdleRate; // Return offered to senior tranche OLib.State state; // Current state of Vault uint256 startAt; // Time when the Vault is unpaused to begin accepting deposits uint256 investAt; // Time when investors can't move funds, strategist can invest uint256 redeemAt; // Time when strategist can redeem LP tokens, investors can withdraw } // Track the asset type and amount in different stages struct Asset { IERC20 token; ITrancheToken trancheToken; uint256 trancheCap; uint256 userCap; uint256 deposited; uint256 originalInvested; uint256 totalInvested; // not literal 1:1, originalInvested + proportional lp from mid-term uint256 received; uint256 rolloverDeposited; } function getState(uint256 _vaultId) external view returns (OLib.State); function createVault(OLib.VaultParams calldata _params) external returns (uint256 vaultId); function deposit( uint256 _vaultId, OLib.Tranche _tranche, uint256 _amount ) external; function depositETH(uint256 _vaultId, OLib.Tranche _tranche) external payable; function depositLp(uint256 _vaultId, uint256 _amount) external returns (uint256 seniorTokensOwed, uint256 juniorTokensOwed); function invest( uint256 _vaultId, uint256 _seniorMinOut, uint256 _juniorMinOut ) external returns (uint256, uint256); function redeem( uint256 _vaultId, uint256 _seniorMinOut, uint256 _juniorMinOut ) external returns (uint256, uint256); function withdraw(uint256 _vaultId, OLib.Tranche _tranche) external returns (uint256); function withdrawETH(uint256 _vaultId, OLib.Tranche _tranche) external returns (uint256); function withdrawLp(uint256 _vaultId, uint256 _amount) external returns (uint256, uint256); function claim(uint256 _vaultId, OLib.Tranche _tranche) external returns (uint256, uint256); function claimETH(uint256 _vaultId, OLib.Tranche _tranche) external returns (uint256, uint256); function depositFromRollover( uint256 _vaultId, uint256 _rolloverId, uint256 _seniorAmount, uint256 _juniorAmount ) external; function rolloverClaim(uint256 _vaultId, uint256 _rolloverId) external returns (uint256, uint256); function setRollover( uint256 _vaultId, address _rollover, uint256 _rolloverId ) external; function canDeposit(uint256 _vaultId) external view returns (bool); // function canTransition(uint256 _vaultId, OLib.State _state) // external // view // returns (bool); function getVaultById(uint256 _vaultId) external view returns (VaultView memory); function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche) external view returns ( uint256 position, uint256 claimableBalance, uint256 withdrawableExcess, uint256 withdrawableBalance ); function seniorExpected(uint256 _vaultId) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "contracts/interfaces/IWETH.sol"; /** * @title Global values used by many contracts * @notice This is mostly used for access control */ interface IRegistry is IAccessControl { function paused() external view returns (bool); function pause() external; function unpause() external; function enableFeatureFlag(bytes32 _featureFlag) external; function disableFeatureFlag(bytes32 _featureFlag) external; function getFeatureFlag(bytes32 _featureFlag) external view returns (bool); function deleteFeatureFlag(bytes32 _featureFlag) external; function denominator() external view returns (uint256); function weth() external view returns (IWETH); function authorized(bytes32 _role, address _account) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/IPairVault.sol"; interface IStrategy { // Additional info stored for each Vault struct Vault { IPairVault origin; // who created this Vault IERC20 pool; // the DEX pool IERC20 senior; // senior asset in pool IERC20 junior; // junior asset in pool uint256 shares; // number of shares for ETF-style mid-duration entry/exit uint256 seniorExcess; // unused senior deposits uint256 juniorExcess; // unused junior deposits } function vaults(uint256 vaultId) external view returns ( IPairVault origin, IERC20 pool, IERC20 senior, IERC20 junior, uint256 shares, uint256 seniorExcess, uint256 juniorExcess ); function addVault( uint256 _vaultId, IERC20 _senior, IERC20 _junior ) external; function addLp(uint256 _vaultId, uint256 _lpTokens) external; function removeLp( uint256 _vaultId, uint256 _shares, address to ) external; function getVaultInfo(uint256 _vaultId) external view returns (IERC20, uint256); function invest( uint256 _vaultId, uint256 _totalSenior, uint256 _totalJunior, uint256 _extraSenior, uint256 _extraJunior, uint256 _seniorMinOut, uint256 _juniorMinOut ) external returns (uint256 seniorInvested, uint256 juniorInvested); function sharesFromLp(uint256 vaultId, uint256 lpTokens) external view returns ( uint256 shares, uint256 vaultShares, IERC20 pool ); function lpFromShares(uint256 vaultId, uint256 shares) external view returns (uint256 lpTokens, uint256 vaultShares); function redeem( uint256 _vaultId, uint256 _seniorExpected, uint256 _seniorMinOut, uint256 _juniorMinOut ) external returns (uint256, uint256); function withdrawExcess( uint256 _vaultId, OLib.Tranche tranche, address to, uint256 amount ) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ITrancheToken is IERC20Upgradeable { function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; function destroy(address payable _receiver) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Arrays.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; //import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Helper functions */ library OLib { using Arrays for uint256[]; // State transition per Vault. Just linear transitions. enum State {Inactive, Deposit, Live, Withdraw} // Only supports 2 tranches for now enum Tranche {Senior, Junior} struct VaultParams { address seniorAsset; address juniorAsset; address strategist; address strategy; uint256 hurdleRate; uint256 startTime; uint256 enrollment; uint256 duration; string seniorName; string seniorSym; string juniorName; string juniorSym; uint256 seniorTrancheCap; uint256 seniorUserCap; uint256 juniorTrancheCap; uint256 juniorUserCap; } struct RolloverParams { address strategist; string seniorName; string seniorSym; string juniorName; string juniorSym; } bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant PANIC_ROLE = keccak256("PANIC_ROLE"); bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE"); bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE"); bytes32 public constant STRATEGIST_ROLE = keccak256("STRATEGIST_ROLE"); bytes32 public constant VAULT_ROLE = keccak256("VAULT_ROLE"); bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE"); bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE"); // Both sums are running sums. If a user deposits [$1, $5, $3], then // userSums would be [$1, $6, $9]. You can figure out the deposit // amount be subtracting userSums[i]-userSum[i-1]. // prefixSums is the total deposited for all investors + this // investors deposit at the time this deposit is made. So at // prefixSum[0], it would be $1 + totalDeposits, where totalDeposits // could be $1000 because other investors have put in money. struct Investor { uint256[] userSums; uint256[] prefixSums; bool claimed; bool withdrawn; } /** * @dev Given the total amount invested by the Vault, we want to find * out how many of this investor's deposits were actually * used. Use findUpperBound on the prefixSum to find the point * where total deposits were accepted. For example, if $2000 was * deposited by all investors and $1000 was invested, then some * position in the prefixSum splits the array into deposits that * got in, and deposits that didn't get in. That same position * maps to userSums. This is the user's deposits that got * in. Since we are keeping track of the sums, we know at that * position the total deposits for a user was $15, even if it was * 15 $1 deposits. And we know the amount that didn't get in is * the last value in userSum - the amount that got it. * @param investor A specific investor * @param invested The total amount invested by this Vault */ function getInvestedAndExcess(Investor storage investor, uint256 invested) internal view returns (uint256 userInvested, uint256 excess) { uint256[] storage prefixSums_ = investor.prefixSums; uint256 length = prefixSums_.length; if (length == 0) { // There were no deposits. Return 0, 0. return (userInvested, excess); } uint256 leastUpperBound = prefixSums_.findUpperBound(invested); if (length == leastUpperBound) { // All deposits got in, no excess. Return total deposits, 0 userInvested = investor.userSums[length - 1]; return (userInvested, excess); } uint256 prefixSum = prefixSums_[leastUpperBound]; if (prefixSum == invested) { // Not all deposits got in, but there are no partial deposits userInvested = investor.userSums[leastUpperBound]; excess = investor.userSums[length - 1] - userInvested; } else { // Let's say some of my deposits got in. The last deposit, // however, was $100 and only $30 got in. Need to split that // deposit so $30 got in, $70 is excess. userInvested = leastUpperBound > 0 ? investor.userSums[leastUpperBound - 1] : 0; uint256 depositAmount = investor.userSums[leastUpperBound] - userInvested; if (prefixSum - depositAmount < invested) { userInvested += (depositAmount + invested - prefixSum); excess = investor.userSums[length - 1] - userInvested; } else { excess = investor.userSums[length - 1] - userInvested; } } } } /** * @title Subset of SafeERC20 from openZeppelin * * @dev Some non-standard ERC20 contracts (e.g. Tether) break * `approve` by forcing it to behave like `safeApprove`. This means * `safeIncreaseAllowance` will fail when it tries to adjust the * allowance. The code below simply adds an extra call to * `approve(spender, 0)`. */ library OndoSaferERC20 { using SafeERC20 for IERC20; function ondoSafeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; token.safeApprove(spender, 0); token.safeApprove(spender, newAllowance); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "contracts/strategies/BasePairLPStrategy.sol"; import "contracts/vendor/uniswap/UniswapV2Library.sol"; import "contracts/vendor/uniswap/SushiSwapLibrary.sol"; import "contracts/Registry.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; /** * @title Access Uniswap * @notice Add and remove liquidity to Uniswap */ abstract contract AUniswapStrategy is BasePairLPStrategy { using SafeERC20 for IERC20; using OndoSaferERC20 for IERC20; // Pointers to Uniswap contracts IUniswapV2Router02 public immutable uniRouter02; uint8 public amm; address public immutable uniFactory; struct Call { address target; bytes data; } /** * @dev * @param _registry Ondo global registry * @param _router Address for UniswapV2Router02 * @param _factory Address for UniswapV2Factory */ constructor( address _registry, address _router, address _factory, uint8 _amm ) BasePairLPStrategy(_registry) { require(_router != address(0) && _factory != address(0), "Invalid target"); require(_amm == 0 || _amm == 1, "Invalid AMM"); amm = _amm; uniRouter02 = IUniswapV2Router02(_router); uniFactory = _factory; } /** * @notice Conversion of LP tokens to shares * @dev Simpler than Sushiswap strat because there's no compounding investment. Shares don't change. * @param vaultId Vault * @param lpTokens Amount of LP tokens * @return Number of shares for LP tokens * @return Total shares for this Vault * @return Uniswap pool */ function sharesFromLp(uint256 vaultId, uint256 lpTokens) external view virtual override returns ( uint256, uint256, IERC20 ) { Vault storage vault_ = vaults[vaultId]; return (lpTokens, vault_.shares, vault_.pool); } /** * @notice Conversion of shares to LP tokens * @param vaultId Vault * @param shares Amount of shares * @return Number LP tokens * @return Total shares for this Vault */ function lpFromShares(uint256 vaultId, uint256 shares) external view virtual override returns (uint256, uint256) { Vault storage vault_ = vaults[vaultId]; return (shares, vault_.shares); } /** * @notice Check whether liquidity pool already exists * @param _senior Asset used for senior tranche * @param _junior Asset used for junior tranche */ function poolExists(IERC20 _senior, IERC20 _junior) internal view returns (bool) { return getPair(address(_senior), address(_junior)) != address(0); } /** * @notice AllPairsVault registers Vault here * @param _vaultId Reference to Vault * @param _senior Asset used for senior tranche * @param _junior Asset used for junior tranche */ function addVault( uint256 _vaultId, IERC20 _senior, IERC20 _junior ) external override nonReentrant isAuthorized(OLib.VAULT_ROLE) { require( address(vaults[_vaultId].origin) == address(0), "Vault id already registered" ); require(poolExists(_senior, _junior), "Pool doesn't exist"); Vault storage vault_ = vaults[_vaultId]; vault_.origin = IPairVault(msg.sender); vault_.pool = IERC20(getPair(address(_senior), address(_junior))); vault_.senior = IERC20(_senior); vault_.junior = IERC20(_junior); } function getPair(address senior, address junior) internal view virtual returns (address) { if (amm == 0) { return UniswapV2Library.pairFor(uniFactory, senior, junior); } else { return SushiSwapLibrary.pairFor(uniFactory, senior, junior); } } /** * @notice Simple wrapper around uniswap * @param amtIn Amount in * @param minOut Minimum out * @param path Router path */ function swapExactIn( uint256 amtIn, uint256 minOut, address[] memory path ) internal returns (uint256) { IERC20(path[0]).ondoSafeIncreaseAllowance(address(uniRouter02), amtIn); return uniRouter02.swapExactTokensForTokens( amtIn, minOut, path, address(this), block.timestamp )[path.length - 1]; } /** * @notice Simple wrapper around uniswap * @param amtOut Amount out * @param maxIn Maximum tokens offered as input * @param path Router path */ function swapExactOut( uint256 amtOut, uint256 maxIn, address[] memory path ) internal returns (uint256) { IERC20(path[0]).ondoSafeIncreaseAllowance(address(uniRouter02), maxIn); return uniRouter02.swapTokensForExactTokens( amtOut, maxIn, path, address(this), block.timestamp )[0]; } /** * @dev Given the total available amounts of senior and junior asset * tokens, invest as much as possible and record any excess uninvested * assets. * @param _vaultId Reference to specific Vault * @param _totalSenior Total amount available to invest into senior assets * @param _totalJunior Total amount available to invest into junior assets * @param _extraSenior Extra funds due to cap on tranche, must be returned * @param _extraJunior Extra funds due to cap on tranche, must be returned * @param _seniorMinIn To ensure you get a decent price * @param _juniorMinIn Same. Passed to addLiquidity on AMM */ function invest( uint256 _vaultId, uint256 _totalSenior, uint256 _totalJunior, uint256 _extraSenior, uint256 _extraJunior, uint256 _seniorMinIn, uint256 _juniorMinIn ) external virtual override nonReentrant whenNotPaused onlyOrigin(_vaultId) returns (uint256 seniorInvested, uint256 juniorInvested) { (seniorInvested, juniorInvested, ) = _invest( _vaultId, _totalSenior, _totalJunior, _extraSenior, _extraJunior, _seniorMinIn, _juniorMinIn ); } function _invest( uint256 _vaultId, uint256 _totalSenior, uint256 _totalJunior, uint256 _extraSenior, uint256 _extraJunior, uint256 _seniorMinIn, uint256 _juniorMinIn ) internal returns ( uint256 seniorInvested, uint256 juniorInvested, uint256 lpTokens ) { Vault storage vault_ = vaults[_vaultId]; vault_.senior.ondoSafeIncreaseAllowance(address(uniRouter02), _totalSenior); vault_.junior.ondoSafeIncreaseAllowance(address(uniRouter02), _totalJunior); (seniorInvested, juniorInvested, lpTokens) = uniRouter02.addLiquidity( address(vault_.senior), address(vault_.junior), _totalSenior, _totalJunior, _seniorMinIn, _juniorMinIn, address(this), block.timestamp ); vault_.shares += lpTokens; vault_.seniorExcess = _totalSenior - seniorInvested + _extraSenior; vault_.juniorExcess = _totalJunior - juniorInvested + _extraJunior; emit Invest(_vaultId, vault_.shares); } // hack to get stack down for redeem function getPath(address _token0, address _token1) internal pure returns (address[] memory path) { path = new address[](2); path[0] = _token0; path[1] = _token1; } function swapForSr( address _senior, address _junior, uint256 _seniorExpected, uint256 seniorReceived, uint256 juniorReceived ) internal returns (uint256, uint256) { uint256 seniorNeeded = _seniorExpected - seniorReceived; address[] memory jr2Sr = getPath(_junior, _senior); if (seniorNeeded > getAmountsOut(juniorReceived, jr2Sr)[1]) { seniorReceived += swapExactIn(juniorReceived, 0, jr2Sr); return (seniorReceived, 0); } else { juniorReceived -= swapExactOut(seniorNeeded, juniorReceived, jr2Sr); return (_seniorExpected, juniorReceived); } } function getAmountsOut(uint256 juniorReceived, address[] memory jr2Sr) internal view virtual returns (uint256[] memory) { if (amm == 0) { return UniswapV2Library.getAmountsOut(uniFactory, juniorReceived, jr2Sr); } else { return SushiSwapLibrary.getAmountsOut(uniFactory, juniorReceived, jr2Sr); } } /** * @dev Convert all LP tokens back into the pair of underlying * assets. Also convert any Sushi equally into both tranches. * The senior tranche is expecting to get paid some hurdle * rate above where they started. Here are the possible outcomes: * - If the senior tranche doesn't have enough, then sell some or * all junior tokens to get the senior to the expected * returns. In the worst case, the senior tranche could suffer * a loss and the junior tranche will be wiped out. * - If the senior tranche has more than enough, reduce this tranche * to the expected payoff. The excess senior tokens should be * converted to junior tokens. * @param _vaultId Reference to a specific Vault * @param _seniorExpected Amount the senior tranche is expecting * @param _seniorMinReceived Compute total for seniorReceived, factoring in slippage * @param _juniorMinReceived Same. * @return seniorReceived Final amount for senior tranche * @return juniorReceived Final amount for junior tranche */ function redeem( uint256 _vaultId, uint256 _seniorExpected, uint256 _seniorMinReceived, uint256 _juniorMinReceived ) external virtual override nonReentrant whenNotPaused onlyOrigin(_vaultId) returns (uint256 seniorReceived, uint256 juniorReceived) { Vault storage vault_ = vaults[_vaultId]; return _redeem( _vaultId, vault_.shares, _seniorExpected, _seniorMinReceived, _juniorMinReceived ); } function _redeem( uint256 _vaultId, uint256 _totaLP, uint256 _seniorExpected, uint256 _seniorMinReceived, uint256 _juniorMinReceived ) internal returns (uint256 seniorReceived, uint256 juniorReceived) { Vault storage vault_ = vaults[_vaultId]; { IERC20 pool = IERC20(vault_.pool); IERC20(pool).ondoSafeIncreaseAllowance(address(uniRouter02), _totaLP); (seniorReceived, juniorReceived) = uniRouter02.removeLiquidity( address(vault_.senior), address(vault_.junior), _totaLP, 0, 0, address(this), block.timestamp ); } if (seniorReceived < _seniorExpected) { (seniorReceived, juniorReceived) = swapForSr( address(vault_.senior), address(vault_.junior), _seniorExpected, seniorReceived, juniorReceived ); } else { if (seniorReceived > _seniorExpected) { juniorReceived += swapExactIn( seniorReceived - _seniorExpected, 0, getPath(address(vault_.senior), address(vault_.junior)) ); } seniorReceived = _seniorExpected; } require( _seniorMinReceived <= seniorReceived && _juniorMinReceived <= juniorReceived, "Too much slippage" ); vault_.senior.ondoSafeIncreaseAllowance( msg.sender, seniorReceived + vault_.seniorExcess ); vault_.junior.ondoSafeIncreaseAllowance( msg.sender, juniorReceived + vault_.juniorExcess ); emit Redeem(_vaultId); return (seniorReceived, juniorReceived); } function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) internal pure returns (uint256) { return (Babylonian.sqrt(reserveIn * (userIn * 3988000 + reserveIn * 3988009)) - reserveIn * 1997) / 1994; } function swapBForA( address a, address b, uint256 aAmount, uint256 bAmount ) internal returns (uint256, uint256) { (uint256 aReserve, uint256 bReserve) = amm == 0 ? UniswapV2Library.getReserves(uniFactory, address(a), address(b)) : SushiSwapLibrary.getReserves(uniFactory, address(a), address(b)); // fancy math to get the amountToSwap uint256 amountToSwap = calculateSwapInAmount(bReserve, bAmount); // subtract bond amount since that amount will be converted to usdc bAmount -= amountToSwap; // convert bond to usdc aAmount += swapExactIn(amountToSwap, 0, getPath(address(b), address(a))); return (aAmount, bAmount); } function sellAForB( address a, address b, uint256 amountA ) internal returns (uint256 bAmount) { bAmount = swapExactIn(amountA, 0, getPath(a, b)); } // you have some quantity of a and b and you want to add liquidity so both can be added as much as possible function investAandB( address a, address b, uint256 amountA, uint256 amountB ) internal returns ( uint256 seniorInvested, uint256 juniorInvested, uint256 lpTokens ) { (seniorInvested, juniorInvested, lpTokens) = addLiquidity( address(a), address(a), amountA, amountB, 0, 0 ); // one of the asssets is now zero or close to zero amountA -= seniorInvested; amountB -= juniorInvested; // if we have more weth then eden, then swap weth for eden, 50/50 if (amountA > amountB) { (amountB, amountA) = swapBForA(b, a, amountB, amountA); } else if (amountB > 0) { (amountA, amountB) = swapBForA(a, b, amountA, amountB); } // if either of the amounts is greater than zero we can try adding liquidity if (amountA > 0 || amountB > 0) { uint256 lpTokens2; (seniorInvested, juniorInvested, lpTokens2) = addLiquidity( a, b, amountA, amountB, 0, 0 ); lpTokens += lpTokens2; } } // you have a single asset and you want to split that with b and add liquidity function investB( address a, address b, uint256 amountA, uint256 amountB ) internal returns ( uint256 seniorInvested, uint256 juniorInvested, uint256 lpTokens ) { (amountA, amountB) = swapBForA(a, b, amountA, amountB); (seniorInvested, juniorInvested, lpTokens) = addLiquidity( a, b, amountA, amountB, 0, 0 ); } function addLiquidity( address token0, address token1, uint256 amt0, uint256 amt1, uint256 minOut0, uint256 minOut1 ) internal returns ( uint256 out0, uint256 out1, uint256 lp ) { IERC20(token0).ondoSafeIncreaseAllowance(address(uniRouter02), amt0); IERC20(token1).ondoSafeIncreaseAllowance(address(uniRouter02), amt1); (out0, out1, lp) = uniRouter02.addLiquidity( token0, token1, amt0, amt1, minOut0, minOut1, address(this), block.timestamp ); } function multiexcall(Call[] calldata calls) external isAuthorized(OLib.GUARDIAN_ROLE) returns (bytes[] memory returnData) { returnData = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory ret) = calls[i].target.call(calls[i].data); require(success, "Multicall aggregate: call failed"); returnData[i] = ret; } } // function _rescueStuckTokens(address[] calldata _tokens) internal override { // super._rescueStuckTokens(_tokens); // } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "contracts/interfaces/IStrategy.sol"; import "contracts/Registry.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/OndoRegistryClient.sol"; import "contracts/interfaces/IPairVault.sol"; /** * @title Basic LP strategy * @notice All LP strategies should inherit from this */ abstract contract BasePairLPStrategy is OndoRegistryClient, IStrategy { using SafeERC20 for IERC20; modifier onlyOrigin(uint256 _vaultId) { require( msg.sender == address(vaults[_vaultId].origin), "Unauthorized: Only Vault contract" ); _; } event Invest(uint256 indexed vault, uint256 lpTokens); event Redeem(uint256 indexed vault); event Harvest(address indexed pool, uint256 lpTokens); mapping(uint256 => Vault) public override vaults; constructor(address _registry) OndoRegistryClient(_registry) {} /** * @notice Deposit more LP tokens while Vault is invested */ function addLp(uint256 _vaultId, uint256 _amount) external virtual override whenNotPaused onlyOrigin(_vaultId) { Vault storage vault_ = vaults[_vaultId]; vault_.shares += _amount; } /** * @notice Remove LP tokens while Vault is invested */ function removeLp( uint256 _vaultId, uint256 _amount, address to ) external virtual override whenNotPaused onlyOrigin(_vaultId) { Vault storage vault_ = vaults[_vaultId]; vault_.shares -= _amount; IERC20(vault_.pool).safeTransfer(to, _amount); } /** * @notice Return the DEX pool and the amount of LP tokens */ function getVaultInfo(uint256 _vaultId) external view override returns (IERC20, uint256) { Vault storage c = vaults[_vaultId]; return (c.pool, c.shares); } /** * @notice Send excess tokens to investor */ function withdrawExcess( uint256 _vaultId, OLib.Tranche tranche, address to, uint256 amount ) external override onlyOrigin(_vaultId) { Vault storage _vault = vaults[_vaultId]; if (tranche == OLib.Tranche.Senior) { uint256 excess = _vault.seniorExcess; require(amount <= excess, "Withdrawing too much"); _vault.seniorExcess -= amount; _vault.senior.safeTransfer(to, amount); } else { uint256 excess = _vault.juniorExcess; require(amount <= excess, "Withdrawing too much"); _vault.juniorExcess -= amount; _vault.junior.safeTransfer(to, amount); } } } pragma solidity 0.8.3; import "contracts/strategies/AUniswapStrategy.sol"; import "contracts/vendor/barnbridge/Staking.sol"; import "contracts/vendor/barnbridge/YieldFarmLP.sol"; import "contracts/libraries/OndoLibrary.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract BondStrategy is AUniswapStrategy { using SafeERC20 for IERC20; using OndoSaferERC20 for IERC20; string public constant name = "Ondo UniswapV2 BOND/USDC Strategy"; uint256 public totalLP; Staking public immutable stakingContract; YieldFarmLp public immutable yieldFarm; IERC20 public immutable bond; IERC20 public immutable usdc; IERC20 public immutable usdcBondUniLp; constructor( address _registry, address _router, address _factory, address _staking, address _yieldFarm, address _usdc, address _bond, address _usdcBondUniLp ) AUniswapStrategy(_registry, _router, _factory, 0) { // AMM 0 stands for uniswap require(_staking != address(0), "staking address cannot be zero"); require(_yieldFarm != address(0), "yieldfarm cannot be zero"); require(_bond != address(0), "bond cannot be zero"); require(_usdc != address(0), "usdc cannot be zero"); require(_usdcBondUniLp != address(0), "usdcBondUniLp cannot be zero"); stakingContract = Staking(_staking); yieldFarm = YieldFarmLp(_yieldFarm); bond = IERC20(_bond); usdc = IERC20(_usdc); usdcBondUniLp = IERC20(_usdcBondUniLp); } function invest( uint256 _vaultId, uint256 _totalSenior, uint256 _totalJunior, uint256 _extraSenior, uint256 _extraJunior, uint256 _seniorMinIn, uint256 _juniorMinIn ) external override nonReentrant whenNotPaused onlyOrigin(_vaultId) returns (uint256 seniorInvested, uint256 juniorInvested) { uint256 lpTokens; (seniorInvested, juniorInvested, lpTokens) = _invest( _vaultId, _totalSenior, _totalJunior, _extraSenior, _extraJunior, _seniorMinIn, _juniorMinIn ); depositIntoStaking(lpTokens); } function redeem( uint256 _vaultId, uint256 _seniorExpected, uint256 _seniorMinReceived, uint256 _juniorMinReceived ) external override nonReentrant whenNotPaused onlyOrigin(_vaultId) returns (uint256 seniorReceived, uint256 juniorReceived) { Vault storage vault_ = vaults[_vaultId]; // withdraw from stakingContract uint256 totalLPBefore = totalLP; withdrawFromStaking(totalLP); (seniorReceived, juniorReceived) = _redeem( _vaultId, totalLPBefore, _seniorExpected, _seniorMinReceived, _juniorMinReceived ); } function depositIntoStaking(uint256 _amount) internal { require(_amount > 0, "amount must be greater than 0"); // increase allowance for our lp tokens usdcBondUniLp.ondoSafeIncreaseAllowance(address(stakingContract), _amount); // deposit into staking stakingContract.deposit(address(usdcBondUniLp), _amount); totalLP += _amount; } function withdrawFromStaking(uint256 _amount) internal { require(_amount > 0, "_amount must be greater than 0"); stakingContract.withdraw(address(usdcBondUniLp), _amount); totalLP -= _amount; } /** * @notice Deposit more LP tokens while Vault is invested */ function addLp(uint256 _vaultId, uint256 _amount) external virtual override whenNotPaused onlyOrigin(_vaultId) { Vault storage vault_ = vaults[_vaultId]; depositIntoStaking(_amount); vault_.shares += _amount; } /** * @notice Remove LP tokens while Vault is invested */ function removeLp( uint256 _vaultId, uint256 _amount, address to ) external virtual override whenNotPaused onlyOrigin(_vaultId) { Vault storage vault_ = vaults[_vaultId]; withdrawFromStaking(_amount); IERC20(vault_.pool).safeTransfer(to, _amount); vault_.shares -= _amount; } function harvest(uint256 _minLp) external nonReentrant whenNotPaused isAuthorized(OLib.STRATEGIST_ROLE) returns (uint256) { uint256 bondAmountBefore = bond.balanceOf(address(this)); // get harvested tokens for all epochs yieldFarm.massHarvest(); uint256 bondAmountAfter = bond.balanceOf(address(this)); // technically can just use balanceOf since all bond balance should be provided as LP uint256 bondAmount = bondAmountAfter - bondAmountBefore; uint256 usdcAmount = 0; uint256 lpTokens = 0; // we know that bond would have increased as part of harvest so now we need to convert the bond to balance with usdc so we can provide more LP if (bondAmount > 10000) { // same interface for uniswap and sushiswap (, , lpTokens) = investB( address(usdc), address(bond), usdcAmount, bondAmount ); // we have more LP now so time to invest that in staking contract // stake new LP tokens in bond depositIntoStaking(lpTokens); } require(lpTokens >= _minLp, "Exceeds maximum slippage"); return lpTokens; } } pragma solidity 0.8.3; interface Staking { function balanceOf(address user, address token) external view returns (uint256); function deposit(address tokenAddress, uint256 amount) external; function withdraw(address tokenAddress, uint256 amount) external; } pragma solidity 0.8.3; interface YieldFarmLp { function massHarvest() external returns (uint256); function harvest(uint128 epochId) external returns (uint256); } pragma solidity >=0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; library SushiSwapLibrary { using SafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } pragma solidity >=0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
function canTransition(uint256 _vaultId, OLib.State _state) external view returns (bool); SPDX-License-Identifier: AGPL-3.0 Global values used by many contracts This is mostly used for access control/
interface IRegistry is IAccessControl { function paused() external view returns (bool); function pause() external; function unpause() external; function enableFeatureFlag(bytes32 _featureFlag) external; function disableFeatureFlag(bytes32 _featureFlag) external; function getFeatureFlag(bytes32 _featureFlag) external view returns (bool); function deleteFeatureFlag(bytes32 _featureFlag) external; function denominator() external view returns (uint256); function weth() external view returns (IWETH); function authorized(bytes32 _role, address _account) external view returns (bool); }
14,555,317
./full_match/43113/0x15BC25e8140dBee142247ea751bA068Ca50e46C4/sources/LendingPool_flat.sol
mint it 1:1 to the amount put inuint256 isFirstDeposit = balances[msg.sender].isFirstDeposit;if (isFirstDeposit == 0) { get fee set first deposit to false balances[msg.sender].isFirstDeposit = 1;} Updates User balancebalances[msg.sender].balance = balances[msg.sender].balance.add(_amount); Update total deposited in the pool_poolTokenSupply = _poolTokenSupply.add(_amount); Lock the poolToken in the contractERC20(poolToken).transferFrom(msg.sender, address(this), _amount);emit Deposit(msg.sender, _amount);
function deposit(uint256 _amount) external { require(_amount > 0, "Can't deposit 0"); _mint(msg.sender, _amount); }
7,154,133
./full_match/1/0x86B32fb3d8b08278cE9EB643EFE59a1a85c15203/sources/bot.sol
If `self` starts with `needle`, `needle` is removed from the beginning of `self`. Otherwise, `self` is unmodified. self The slice to operate on. needle The slice to search for. return `self`/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; }
4,891,417
./full_match/5/0xd9d8b4dfD53319aDDfcDb2E6cE6c317FE288D19B/sources/contracts/ecosystem/RandToken.sol
Function to allow admins to move funds without multiple approve and transfer steps Aims to allow simple UX owner is the address who's tokens are approved and transferred recipient is the address where to transfer the funds amount is the amount of transfer
function safetyModuleTransfer( address owner, address recipient, uint256 amount ) external whenNotPaused { require( REGISTRY.getAddressOf(SAFETY_MODULE) == _msgSender(), "RND: Not accessible by msg.sender" ); _transfer(owner, recipient, amount); }
1,876,454
./partial_match/1/0x5505054d8a85a6024d81857BF43f52D767970587/sources/Treasury.sol
Returns amount of excess reserves return value_ Excess reserves
function excessReserves() external view returns (uint256 value_) { uint256 _balance = IERC20(WETH).balanceOf(address(this)); uint256 _value = (_balance * 1e9) / BACKING; if (IERC20(QWT).totalSupply() > _value) return 0; return (_value - IERC20(QWT).totalSupply()); }
11,029,685
./full_match/1/0xD975C2E388179B741401F0e88879090751bb1acD/sources/contracts/doods.sol
require(freemintActive, "free mint is not active.");
function flipSale() public onlyOwner { saleActive = !saleActive; }
9,823,447
./full_match/11155111/0xb12C52dc4D8ADb4fe7DB08A2D9b1D191abb4AB04/sources/src/TokenFactory.sol
deploy contract with CREATE2 opcode/
function deploy( bytes memory bytecode, uint256 salt ) internal returns (address addr) { assembly { addr := create2( callvalue(), add(bytecode, 0x20), mload(bytecode), salt ) if iszero(extcodesize(addr)) { revert(0, 0) } } emit DeployedToken(addr, salt); }
3,812,575
./full_match/5/0x02B727D7ac6B48e7D110E2ac3F9c98e9177AfCE7/sources/contracts/shnucoin.sol
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) public isOwner virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); }
1,868,671
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/Marketplace.sol
Verifies Brightlist For Presale Fixed Price Sale/
function VerifyBrightListWithPriority(uint SaleIndex, address _Wallet, bytes32 _Root, bytes32[] calldata _Proof) public view returns (bool, uint) { bytes32 _Leaf = keccak256(abi.encodePacked(_Wallet)); return (false, 69420); }
8,471,328
/** *Submitted for verification at Etherscan.io on 2020-08-11 */ pragma solidity 0.6.0; /** * @title Offering contract * @dev Offering logic and mining logic */ contract Nest_NToken_OfferMain { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; // Offering data structure struct Nest_NToken_OfferPriceData { // The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress()) address owner; // Offering owner bool deviate; // Whether it deviates address tokenAddress; // The erc20 contract address of the target offer token uint256 ethAmount; // The ETH amount in the offer list uint256 tokenAmount; // The token amount in the offer list uint256 dealEthAmount; // The remaining number of tradable ETH uint256 dealTokenAmount; // The remaining number of tradable tokens uint256 blockNum; // The block number where the offer is located uint256 serviceCharge; // The fee for mining // Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0 } Nest_NToken_OfferPriceData [] _prices; // Array used to save offers Nest_3_VoteFactory _voteFactory; // Voting contract Nest_3_OfferPrice _offerPrice; // Price contract Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract ERC20 _nestToken; // nestToken Nest_3_Abonus _abonus; // Bonus pool uint256 _miningETH = 10; // Offering mining fee ratio uint256 _tranEth = 1; // Taker fee ratio uint256 _tranAddition = 2; // Additional transaction multiple uint256 _leastEth = 10 ether; // Minimum offer of ETH uint256 _offerSpan = 10 ether; // ETH Offering span uint256 _deviate = 10; // Price deviation - 10% uint256 _deviationFromScale = 10; // Deviation from asset scale uint256 _ownerMining = 5; // Creator ratio uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount uint32 _blockLimit = 25; // Block interval upper limit uint256 _blockAttenuation = 2400000; // Block decay interval mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount uint256[10] _attenuationAmount; // Mining decay list // Log token contract address event OfferTokenContractAddress(address contractAddress); // Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining); // Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); // Log current block, current block mined amount, token address event OreDrawingLog(uint256 nowBlock, uint256 blockAmount, address tokenAddress); // Log offering block, token address, token offered times event MiningLog(uint256 blockNum, address tokenAddress, uint256 offerTimes); /** * Initialization method * @param voteFactory Voting contract address **/ constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); uint256 blockAmount = 4 ether; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(8).div(10); } } /** * Reset voting contract method * @param voteFactory Voting contract address **/ function changeMapping(address voteFactory) public onlyOwner { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.checkAddress("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping"))); } /** * Offering method * @param ethAmount ETH amount * @param erc20Amount Erc20 token amount * @param erc20Address Erc20 token address **/ function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); address nTokenAddress = _tokenMapping.checkTokenMapping(erc20Address); require(nTokenAddress != address(0x0)); // Judge whether the price deviates uint256 ethMining; bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address); if (isDeviate) { require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale"); ethMining = _leastEth.mul(_miningETH).div(1000); } else { ethMining = ethAmount.mul(_miningETH).div(1000); } require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee"); uint256 subValue = msg.value.sub(ethAmount.add(ethMining)); if (subValue > 0) { repayEth(address(msg.sender), subValue); } // Create an offer createOffer(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining); // Transfer in offer asset - erc20 to this contract ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount); _abonus.switchToEthForNTokenOffer.value(ethMining)(nTokenAddress); // Mining if (_blockOfferAmount[block.number][erc20Address] == 0) { uint256 miningAmount = oreDrawing(nTokenAddress); Nest_NToken nToken = Nest_NToken(nTokenAddress); nToken.transfer(nToken.checkBidder(), miningAmount.mul(_ownerMining).div(100)); _blockMining[block.number][erc20Address] = miningAmount.sub(miningAmount.mul(_ownerMining).div(100)); } _blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].add(ethMining); } /** * @dev Create offer * @param ethAmount Offering ETH amount * @param erc20Amount Offering erc20 amount * @param erc20Address Offering erc20 address **/ function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private { // Check offer conditions require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); // Create offering contract emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_NToken_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); // Record price _offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender)); } // Convert offer address into index in offer array function toIndex(address contractAddress) public pure returns(uint256) { return uint256(contractAddress); } // Convert index in offer array into offer address function toAddress(uint256 index) public pure returns(address) { return address(index); } /** * Withdraw offer assets * @param contractAddress Offer address **/ function turnOut(address contractAddress) public { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData storage offerPriceData = _prices[index]; require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error"); // Withdraw ETH if (offerPriceData.ethAmount > 0) { uint256 payEth = offerPriceData.ethAmount; offerPriceData.ethAmount = 0; repayEth(offerPriceData.owner, payEth); } // Withdraw erc20 if (offerPriceData.tokenAmount > 0) { uint256 payErc = offerPriceData.tokenAmount; offerPriceData.tokenAmount = 0; ERC20(address(offerPriceData.tokenAddress)).safeTransfer(address(offerPriceData.owner), payErc); } // Mining settlement if (offerPriceData.serviceCharge > 0) { mining(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner); offerPriceData.serviceCharge = 0; } } /** * @dev Taker order - pay ETH and buy erc20 * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract if (tokenAmount > tranTokenAmount) { ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount)); } else { ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount)); } // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress); _abonus.switchToEth.value(serviceCharge)(nTokenAddress); } } /** * @dev Taker order - pay erc20 and buy ETH * @param ethAmount The amount of ETH of this offer * @param tokenAmount The amount of erc20 of this offer * @param contractAddress The target offer address * @param tranEthAmount The amount of ETH of taker order * @param tranTokenAmount The amount of erc20 of taker order * @param tranTokenAddress The erc20 address of taker order */ function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000); require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = toIndex(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount)); // Modify price _offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit)); emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress); _abonus.switchToEth.value(serviceCharge)(nTokenAddress); } } /** * Offering mining * @param ntoken NToken address **/ function oreDrawing(address ntoken) private returns(uint256) { Nest_NToken miningToken = Nest_NToken(ntoken); (uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.checkBlockInfo(); uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation); uint256 miningAmount = 0; uint256 attenuation; if (attenuationPointNow > 9) { attenuation = _afterMiningAmount; } else { attenuation = _attenuationAmount[attenuationPointNow]; } miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock)); miningToken.increaseTotal(miningAmount); emit OreDrawingLog(block.number, miningAmount, ntoken); return miningAmount; } /** * Retrieve mining * @param token Token address **/ function mining(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) { // Block mining amount*offer fee/block offer fee uint256 miningAmount = _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]); // Transfer NToken Nest_NToken nToken = Nest_NToken(address(_tokenMapping.checkTokenMapping(token))); require(nToken.transfer(address(owner), miningAmount), "Transfer failure"); emit MiningLog(blockNum, token,_blockOfferAmount[blockNum][token]); return miningAmount; } // Compare order prices function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { (uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token); if (frontEthValue == 0 || frontTokenValue == 0) { return false; } uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue <= maxTokenAmount) { uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100)); if (myTokenValue >= minTokenAmount) { return false; } } return true; } // Check contract status function checkContractState(uint256 createBlock) public view returns (uint256) { if (block.number.sub(createBlock) > _blockLimit) { return 1; } return 0; } // Transfer ETH function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // View the upper limit of the block interval function checkBlockLimit() public view returns(uint256) { return _blockLimit; } // View taker fee ratio function checkTranEth() public view returns (uint256) { return _tranEth; } // View additional transaction multiple function checkTranAddition() public view returns(uint256) { return _tranAddition; } // View minimum offering ETH function checkleastEth() public view returns(uint256) { return _leastEth; } // View offering ETH span function checkOfferSpan() public view returns(uint256) { return _offerSpan; } // View block offering amount function checkBlockOfferAmount(uint256 blockNum, address token) public view returns (uint256) { return _blockOfferAmount[blockNum][token]; } // View offering block mining amount function checkBlockMining(uint256 blockNum, address token) public view returns (uint256) { return _blockMining[blockNum][token]; } // View offering mining amount function checkOfferMining(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) { if (serviceCharge == 0) { return 0; } else { return _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]); } } // View the owner allocation ratio function checkOwnerMining() public view returns(uint256) { return _ownerMining; } // View the mining decay function checkAttenuationAmount(uint256 num) public view returns(uint256) { return _attenuationAmount[num]; } // Modify taker order fee ratio function changeTranEth(uint256 num) public onlyOwner { _tranEth = num; } // Modify block interval upper limit function changeBlockLimit(uint32 num) public onlyOwner { _blockLimit = num; } // Modify additional transaction multiple function changeTranAddition(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _tranAddition = num; } // Modify minimum offering ETH function changeLeastEth(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _leastEth = num; } // Modify offering ETH span function changeOfferSpan(uint256 num) public onlyOwner { require(num > 0, "Parameter needs to be greater than 0"); _offerSpan = num; } // Modify price deviation function changekDeviate(uint256 num) public onlyOwner { _deviate = num; } // Modify the deviation from scale function changeDeviationFromScale(uint256 num) public onlyOwner { _deviationFromScale = num; } // Modify the owner allocation ratio function changeOwnerMining(uint256 num) public onlyOwner { _ownerMining = num; } // Modify the mining decay function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner { uint256 blockAmount = firstAmount; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.mul(top).div(bottom); } } // Vote administrators only modifier onlyOwner(){ require(_voteFactory.checkOwners(msg.sender), "No authority"); _; } /** * Get the number of offers stored in the offer array * @return The number of offers stored in the offer array **/ function getPriceCount() view public returns (uint256) { return _prices.length; } /** * Get offer information according to the index * @param priceIndex Offer index * @return Offer information **/ function getPrice(uint256 priceIndex) view public returns (string memory) { // The buffer array used to generate the result string bytes memory buf = new bytes(500000); uint256 index = 0; index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index); // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Search the contract address list of the target account (reverse order) * @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address) * @param count Maximum number of records to return * @param maxFindCount The max index to search * @param owner Target account address * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Calculate search interval i and end uint256 i = _prices.length; uint256 end = 0; if (start != address(0)) { i = toIndex(start); } if (i > maxFindCount) { end = i - maxFindCount; } // Loop search, write qualified records into buffer while (count > 0 && i-- > end) { Nest_NToken_OfferPriceData memory price = _prices[i]; if (price.owner == owner) { --count; index = writeOfferPriceData(i, price, buf, index); } } // Generate result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } /** * Get the list of offers by page * @param offset Skip the first offset records * @param count Maximum number of records to return * @param order Sort rules. 0 means reverse order, non-zero means positive order * @return Separate the offer records with symbols. use , to divide fields: * uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge **/ function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Find search interval i and end uint256 i = 0; uint256 end = 0; if (order == 0) { // Reverse order, in default // Calculate search interval i and end if (offset < _prices.length) { i = _prices.length - offset; } if (count < i) { end = i - count; } // Write records in the target interval into the buffer while (i-- > end) { index = writeOfferPriceData(i, _prices[i], buf, index); } } else { // Ascending order // Calculate the search interval i and end if (offset < _prices.length) { i = offset; } else { i = _prices.length; } end = i + count; if(end > _prices.length) { end = _prices.length; } // Write the records in the target interval into the buffer while (i < end) { index = writeOfferPriceData(i, _prices[i], buf, index); ++i; } } // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } // Write the offer data into the buffer and return the buffer index function writeOfferPriceData(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { index = writeAddress(toAddress(priceIndex), buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.owner, buf, index); buf[index++] = byte(uint8(44)); index = writeAddress(price.tokenAddress, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.ethAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.tokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealEthAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.dealTokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.blockNum, buf, index); buf[index++] = byte(uint8(44)); index = writeUInt(price.serviceCharge, buf, index); buf[index++] = byte(uint8(44)); return index; } // Convert integer to string in decimal form, write the string into the buffer, and return the buffer index function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { uint256 i = index; do { buf[index++] = byte(uint8(iv % 10 +48)); iv /= 10; } while (iv > 0); for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { uint256 iv = uint256(addr); uint256 i = index + 40; do { uint256 w = iv % 16; if(w < 10) { buf[index++] = byte(uint8(w +48)); } else { buf[index++] = byte(uint8(w +87)); } iv /= 16; } while (index < i); i -= 40; for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } } // Price contract interface Nest_3_OfferPrice { // Add price data function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) external; // Modify price function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external; function updateAndCheckPricePrivate(address tokenAddress) external view returns(uint256 ethAmount, uint256 erc20Amount); } // Voting contract interface Nest_3_VoteFactory { // Check address function checkAddress(string calldata name) external view returns (address contractAddress); // Check whether an administrator function checkOwners(address man) external view returns (bool); } // NToken contract interface Nest_NToken { // Additional issuance function increaseTotal(uint256 value) external; // Check mining information function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); // Check creator function checkBidder() external view returns(address); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // NToken mapping contract interface Nest_NToken_TokenMapping { // Check token mapping function checkTokenMapping(address token) external view returns (address); } // Bonus pool contract interface Nest_3_Abonus { function switchToEth(address token) external payable; function switchToEthForNTokenOffer(address token) external payable; } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library address_make_payable { function make_payable(address x) internal pure returns (address payable) { return address(uint160(x)); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(ERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface ERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
Create offer ethAmount Offering ETH amount erc20Amount Offering erc20 amount erc20Address Offering erc20 address/ Check offer conditions Create offering contract Record price
function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private { require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_NToken_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); _offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender)); }
7,993,948
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // 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 (last updated v4.5.0) (token/ERC721/ERC721.sol) 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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/ERC721Royalty.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../common/ERC2981.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty payment * information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC721Royalty is ERC2981, ERC721 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); _resetTokenRoyalty(tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol) pragma solidity ^0.8.0; import "../../interfaces/IERC2981.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the * fee is specified in basis points by default. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC2981 is IERC2981, ERC165 { struct RoyaltyInfo { address receiver; uint96 royaltyFraction; } RoyaltyInfo private _defaultRoyaltyInfo; mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc IERC2981 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } /** * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an * override. */ function _feeDenominator() internal pure virtual returns (uint96) { return 10000; } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: invalid receiver"); _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Removes default royalty information. */ function _deleteDefaultRoyalty() internal virtual { delete _defaultRoyaltyInfo; } /** * @dev Sets the royalty information for a specific token id, overriding the global default. * * Requirements: * * - `tokenId` must be already minted. * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator ) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: Invalid parameters"); _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Resets royalty information for the token id back to the global default. */ function _resetTokenRoyalty(uint256 tokenId) internal virtual { delete _tokenRoyaltyInfo[tokenId]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: 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); } pragma solidity ^0.8.11; // SPDX-License-Identifier: UNLICENSED import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Royalty.sol"; contract CrypteesToken is ERC721, ERC721Pausable, ERC721Royalty, Ownable { event TokenCreated(string uuid, address to); event BaseURISet(string uri); address public proxyMinter; // only account that can call mintFor() string private _baseTokenURI; mapping (uint256 => bytes32) private tokenIdToUuid; // Maps token id to UUID mapping (bytes32 => uint256) private uuidToTokenId; // Maps UUID to token id mapping (uint256 => string) private tokenURIMap; constructor(string memory baseTokenURI) ERC721("Cryptees", "Cryptees") { _baseTokenURI = baseTokenURI; proxyMinter = _msgSender(); setDefaultRoyalty(_msgSender(), 1000); } function setTokenRoyalty(uint256 tokenId, address recipient, uint96 feeNumerator) public onlyOwner { _setTokenRoyalty(tokenId, recipient, feeNumerator); } function setDefaultRoyalty(address recipient, uint96 fraction) public onlyOwner { _setDefaultRoyalty(recipient, fraction); } function deleteDefaultRoyalty() public onlyOwner { _deleteDefaultRoyalty(); } function createToken(uint256 tokenId, string memory uuid, address to) public onlyOwner { bytes32 uuidBytes32 = UUIDStringToBytes32(uuid); createTokenWithId(tokenId, uuidBytes32, to); } function burn(uint256 tokenId) public onlyOwner { _burn(tokenId); } function mintFor(address to, uint256 amount, bytes memory mintingBlob) public { require(proxyMinter == _msgSender(), "Caller is not the proxy minter."); (uint256[] memory tokenIds, bytes32[] memory uuids) = parseMintingBlob(mintingBlob, amount); for (uint i; i < tokenIds.length; i++) { createTokenWithId(tokenIds[i], uuids[i], to); } } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Royalty, ERC721) returns (bool) { return super.supportsInterface(interfaceId); } function getTokenIdOfUUID(string memory uuid) public view returns (uint256) { bytes32 uuid32 = UUIDStringToBytes32(uuid); require(uuidExists(uuid32), "UUID does not exist."); return uuidToTokenId[uuid32]; } function getUUIDOfTokenId(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Token does not exist."); return bytes32ToUUIDString(tokenIdToUuid[tokenId]); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (bytes(tokenURIMap[tokenId]).length > 0) { return tokenURIMap[tokenId]; } string memory uuid = bytes32ToUUIDString(tokenIdToUuid[tokenId]); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, uuid)) : ''; } function setBaseTokenURI(string memory uri) public onlyOwner { _baseTokenURI = uri; emit BaseURISet(uri); } function setTokenURI(uint256 tokenId, string memory uri) public onlyOwner { tokenURIMap[tokenId] = uri; } function clearTokenURI(uint256 tokenId) public onlyOwner { delete tokenURIMap[tokenId]; } function pause() public virtual onlyOwner { _pause(); } function unpause() public virtual onlyOwner { _unpause(); } function setProxyMinter(address proxy) public onlyOwner { proxyMinter = proxy; } // ------- Internal functions below here: function createTokenWithId(uint256 tokenId, bytes32 uuid, address to) internal { require(!_exists(tokenId), "Token already exists."); _safeMint(to, tokenId); uuidToTokenId[uuid] = tokenId; tokenIdToUuid[tokenId] = uuid; emit TokenCreated(bytes32ToUUIDString(uuid), to); } // Parses a mintingBlob with {tokenId1}:{uuid1}{tokenId2}:{uuid2} and then returns them // Example: {1}:{e9071858-e63b-4f27-92d7-0603235c0b8c}{2}:{f23a1b52-e63b-3f77-42d7-3603235c1b42} function parseMintingBlob(bytes memory mintingBlob, uint256 amount) internal pure returns (uint256[] memory, bytes32[] memory) { uint256 offset = 0; uint256[] memory tokenIds = new uint256[](amount); bytes32[] memory uuids = new bytes32[](amount); bool isTokenId = true; for (uint i; i < mintingBlob.length; i++) { if (mintingBlob[i] == "{") { if (isTokenId) { (uint256 tokenId, uint256 nextItem) = parseMintingBlobTokenId(mintingBlob, i + 1); tokenIds[offset] = tokenId; isTokenId = false; i = nextItem; } else { (bytes32 uuid, uint256 nextItem) = parseMintingBlobUUID(mintingBlob, i + 1); uuids[offset] = uuid; isTokenId = true; offset++; i = nextItem; } } } return (tokenIds, uuids); } function parseMintingBlobTokenId(bytes memory mintingBlob, uint start) internal pure returns (uint256, uint256) { uint256 result = 0; for (uint256 i = start; i < mintingBlob.length; i++) { if (mintingBlob[i] == "}") { return (result, i); } result = (result * 10) + (uint8(mintingBlob[i]) - 48); } return (result, mintingBlob.length); } function parseMintingBlobUUID(bytes memory mintingBlob, uint start) internal pure returns (bytes32, uint256) { bytes memory temp = new bytes(32); bytes32 result; uint32 index; for (uint i = start; i < mintingBlob.length; i++) { if (mintingBlob[i] == "}") { assembly { result := mload(add(temp, 32)) } return (result, i); } if (mintingBlob[i] == "-") { continue; } temp[index] = mintingBlob[i]; index++; } assembly { result := mload(add(temp, 32)) } return (result, mintingBlob.length); } function uuidExists(bytes32 uuid) internal view returns (bool) { return uuidToTokenId[uuid] != 0; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721Royalty, ERC721) { super._burn(tokenId); _resetTokenRoyalty(tokenId); } // Converts a bytes32 UUID to a UUID string with dashes // e9071858e63b4f2792d70603235c0b8c => e9071858-e63b-4f27-92d7-0603235c0b8c function bytes32ToUUIDString(bytes32 b) internal pure returns (string memory) { bytes memory bytesArray = new bytes(36); uint j; for (uint256 i; i < 32; i++) { bytesArray[j] = b[i]; // Add back in dashes at correct positions if (i == 7 || i == 11 || i == 15 || i == 19) { j++; bytesArray[j] = "-"; } j++; } return string(bytesArray); } // Converts a UUID string with dashes into a bytes32 UUID without dashes // e9071858-e63b-4f27-92d7-0603235c0b8c => e9071858e63b4f2792d70603235c0b8c function UUIDStringToBytes32(string memory s) internal pure returns (bytes32) { bytes memory bytesArray = bytes(s); bytes memory noDashes = new bytes(32); uint index; for (uint256 i; i < bytesArray.length; i++) { if (bytesArray[i] == "-") { continue; } noDashes[index] = bytesArray[i]; index++; } bytes32 result; assembly { result := mload(add(noDashes, 32)) } return result; } }
------- Internal functions below here:
function createTokenWithId(uint256 tokenId, bytes32 uuid, address to) internal { require(!_exists(tokenId), "Token already exists."); _safeMint(to, tokenId); uuidToTokenId[uuid] = tokenId; tokenIdToUuid[tokenId] = uuid; emit TokenCreated(bytes32ToUUIDString(uuid), to); }
485,234
./partial_match/4/0x8619ce3bd7827AA4bD0E9787EE27e74FBb3A2Dfa/sources/SmolStudio.sol
Will emit a specific URI log event for corresponding token _tokenIDs IDs of the token corresponding to the _uris logged _URIs The URIs of the specified _tokenIDs/
function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "erc1155metadata#_loguris: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } }
8,581,220
./partial_match/56/0x956BcE4F086dC4579B960ED80336Ef79737cDaa3/sources/StrategyVenusBNBV2.sol
Updates the risk profile and rebalances the vault funds accordingly. _borrowRate percent to borrow on each leverage level. _borrowDepth how many levels to leverage the funds./
function rebalance(uint256 _borrowRate, uint256 _borrowDepth) external onlyOwner { require(_borrowRate <= BORROW_RATE_MAX, "!rate"); require(_borrowDepth <= BORROW_DEPTH_MAX, "!depth"); _deleverage(); borrowRate = _borrowRate; borrowDepth = _borrowDepth; _leverage(address(this).balance); StratRebalance(_borrowRate, _borrowDepth); }
11,337,917
./full_match/11155111/0x298F37fFd4B31d216B8954968cEe7EC5273CB891/sources/src/Streams.sol
Extracts streamId from a `StreamConfig` `config` has value: `streamId (32 bits) | amtPerSec (160 bits) | start (32 bits) | duration (32 bits)` By bit shifting we get value: `zeros (224 bits) | streamId (32 bits)` By casting down we get value: `streamId (32 bits)`
function streamId(StreamConfig config) internal pure returns (uint32) { return uint32(StreamConfig.unwrap(config) >> 224); }
3,819,411
./partial_match/1/0x0429D0A028D6A8a6Ea50eAaCfe1137bB30156E9d/sources/TradeAccounting.sol
File: contracts/interface/ISystemSettings.sol
interface ISystemSettings { function issuanceRatio() external view returns(uint); }
2,670,621
./full_match/4/0xFa7C4A968A072beB9210ecb93C98d1ccE61e189c/sources/browser/GameShop.sol
check if accounts already contains the address of the player
function containsAddress(address _address) private returns (bool){ return accounts[_address]; }
13,339,268
// 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"; import './Mars26.sol'; import './MarsStorage.sol'; /** * @title Mars contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract Mars is Ownable, ERC721Enumerable { using SafeMath for uint256; bytes32 private _provenanceHash; uint256 internal _maxSupply; uint256 private _nameChangePrice; uint256 private _saleStartTimestamp; uint256 private _revealTimestamp; uint256[6] private _priceIntervalSupplyLimits; uint256 private _startingIndexBlock; uint256 internal _startingIndex; mapping (uint256 => string) private _tokenNames; mapping (string => bool) private _reservedNames; mapping (uint256 => bool) private _mintedBeforeReveal; Mars26 private _m26; MarsStorage private _storage; event NameChange (uint256 indexed maskIndex, string newName); /** * @dev Sets immutable values of contract. */ constructor ( bytes32 provenanceHash_, address m26Address_, uint256 nameChangePrice_, uint256 saleStartTimestamp_, uint256 revealTimestamp_, uint256 maxSupply_, uint256[6] memory priceIntervalSupplyLimits_ ) ERC721("Mars", "MARS") { _provenanceHash = provenanceHash_; _m26 = Mars26(m26Address_); _nameChangePrice = nameChangePrice_; _saleStartTimestamp = saleStartTimestamp_; _revealTimestamp = revealTimestamp_; for (uint i = 1; i < priceIntervalSupplyLimits_.length; i++) { require( priceIntervalSupplyLimits_[i - 1] < priceIntervalSupplyLimits_[i], "Price intervale supply limit need to ascending" ); } _priceIntervalSupplyLimits = priceIntervalSupplyLimits_; _maxSupply = maxSupply_; _storage = new MarsStorage(maxSupply_); } /** * @dev Returns provenance hash digest set during initialization of contract. * * The provenance hash is derived by concatenating all existing IPFS CIDs (v0) * of the Mars NFTs and hashing the concatenated string using SHA2-256. * Note that the CIDs were concatenated and hashed in their base58 representation. */ function provenanceHash() public view returns (bytes32) { return _provenanceHash; } /** * @dev Returns address of Mars26 ERC-20 token contract. */ function m26Address() public view returns (address) { return address(_m26); } /** * @dev Returns address of connected storage contract. */ function storageAddress() public view returns (address) { return address(_storage); } /** * @dev Returns max number of NFTs that can be minted. */ function maxSupply() public view returns (uint256) { return _maxSupply; } /** * @dev Returns the MNCT price for changing the name of a token. */ function nameChangePrice() public view returns (uint256) { return _nameChangePrice; } /** * @dev Returns the start timestamp of the initial sale. */ function saleStartTimestamp() public view returns (uint256) { return _saleStartTimestamp; } /** * @dev Returns the reveal timestamp after which the token ids will be assigned. */ function revealTimestamp() public view returns (uint256) { return _revealTimestamp; } /** * @dev Returns the set upper supply limits which determine the NFT price during sale. */ function priceIntervalSupplyLimits() public view returns (uint256[6] memory) { return _priceIntervalSupplyLimits; } /** * @dev Returns the randomized starting index to assign and reveal token ids to * intial sequence of NFTs. */ function startingIndex() public view returns (uint256) { return _startingIndex; } /** * @dev Returns the randomized starting index block which is used to derive * {_startingIndex} from. */ function startingIndexBlock() public view returns (uint256) { return _startingIndexBlock; } /** * @dev See {MarsStorage.initialSequenceTokenCID} */ function initialSequenceTokenCID(uint256 initialSequenceIndex) public view returns (string memory) { return _storage.initialSequenceTokenCID(initialSequenceIndex); } /** * @dev Returns if {nameString} has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _reservedNames[_toLower(nameString)]; } /** * @dev Returns reverved name for given token id. */ function tokenNames(uint256 tokenId) public view returns (string memory) { return _tokenNames[tokenId]; } /** * @dev Returns the set token URI, i.e. IPFS v0 CID, of {tokenId}. * Prefixed with ipfs:// */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); require(_startingIndex > 0, "Tokens have not been assigned yet"); uint256 initialSequenceIndex = _toInitialSequenceIndex(tokenId); return tokenURIOfInitialSequenceIndex(initialSequenceIndex); } /** * @dev Returns the set token URI, i.e. IPFS v0 CID, of {initialSequenceIndex}. * Prefixed with ipfs:// */ function tokenURIOfInitialSequenceIndex(uint256 initialSequenceIndex) public view returns (string memory) { require(_startingIndex > 0, "Tokens have not been assigned yet"); string memory tokenCID = initialSequenceTokenCID(initialSequenceIndex); string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return tokenCID; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(tokenCID).length > 0) { return string(abi.encodePacked(base, tokenCID)); } return base; } /** * @dev Returns if the NFT has been minted before reveal phase. */ function isMintedBeforeReveal(uint256 index) public view returns (bool) { return _mintedBeforeReveal[index]; } /** * @dev Gets current NFT price based on already minted tokens. */ function getNFTPrice() public view returns (uint256) { uint currentSupply = totalSupply(); if (currentSupply < _priceIntervalSupplyLimits[0]) { return 0.05 ether; } else if (currentSupply < _priceIntervalSupplyLimits[1]) { return 0.1 ether; } else if (currentSupply < _priceIntervalSupplyLimits[2]) { return 0.2 ether; } else if (currentSupply < _priceIntervalSupplyLimits[3]) { return 0.4 ether; } else if (currentSupply < _priceIntervalSupplyLimits[4]) { return 1 ether; } else if (currentSupply < _priceIntervalSupplyLimits[5]) { return 3 ether; } else { return 26 ether; } } /** * @dev Mints Mars NFTs */ function mintNFT(uint256 numberOfNfts) public payable { require(block.timestamp >= _saleStartTimestamp, "Sale has not started"); require(totalSupply() < _maxSupply, "Sale has already ended"); require(numberOfNfts > 0, "Cannot buy 0 NFTs"); require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once"); require(totalSupply().add(numberOfNfts) <= _maxSupply, "Exceeds max number of NFTs in existence"); require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); require(mintIndex < _maxSupply, "Exceeds max number of NFTs in existence"); if (block.timestamp < _revealTimestamp) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } // Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense if (_startingIndexBlock == 0 && (totalSupply() == _maxSupply || block.timestamp >= _revealTimestamp)) { _startingIndexBlock = block.number; } } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(_startingIndex == 0, "Starting index is already set"); require(_startingIndexBlock != 0, "Starting index block must be set"); _startingIndex = uint(blockhash(_startingIndexBlock)) % _maxSupply; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(_startingIndexBlock) > 255) { _startingIndex = uint(blockhash(block.number - 1)) % _maxSupply; } // Prevent default sequence if (_startingIndex == 0) { _startingIndex = _startingIndex.add(1); } } /** * @dev Changes the name for Mars tile tokenId */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(_validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenNames[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); _m26.transferFrom(msg.sender, address(this), _nameChangePrice); // If already named, dereserve old name if (bytes(_tokenNames[tokenId]).length > 0) { _toggleReserveName(_tokenNames[tokenId], false); } _toggleReserveName(newName, true); _tokenNames[tokenId] = newName; _m26.burn(_nameChangePrice); emit NameChange(tokenId, newName); } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() onlyOwner public { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev See {MarsStorage.setInitialSequenceTokenHashes} */ function setInitialSequenceTokenHashes(bytes32[] memory tokenHashes) onlyOwner public { _storage.setInitialSequenceTokenHashes(tokenHashes); } /** * @dev See {MarsStorage.setInitialSequenceTokenHashesAtIndex} */ function setInitialSequenceTokenHashesAtIndex( uint256 startIndex, bytes32[] memory tokenHashes ) public onlyOwner { _storage.setInitialSequenceTokenHashesAtIndex(startIndex, tokenHashes); } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function _validateName(string memory str) private pure returns (bool){ bytes memory b = bytes(str); if (b.length < 1) return false; if (b.length > 50) return false; // Cannot be longer than 25 characters if (b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for (uint i; i < b.length; i++) { bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if ( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function _toLower(string memory str) private pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function _toggleReserveName(string memory str, bool isReserve) internal { _reservedNames[_toLower(str)] = isReserve; } function _baseURI() internal pure override returns (string memory) { return "ipfs://"; } function _toInitialSequenceIndex(uint256 tokenId) internal view returns (uint256) { return (tokenId + _startingIndex) % _maxSupply; } } // 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 () { 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.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./Mars.sol"; /** * Mars26 Contract * @dev Extends standard ERC20 contract */ contract Mars26 is ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public constant INITIAL_ALLOTMENT = 2026 * (10 ** 18); uint256 public constant PRE_REVEAL_MULTIPLIER = 2; uint256 private constant _SECONDS_IN_A_DAY = 86400; uint256 private _emissionStartTimestamp; uint256 private _emissionEndTimestamp; uint256 private _emissionPerDay; mapping(uint256 => uint256) private _lastClaim; Mars private _mars; /** * @dev Sets immutable values of contract. */ constructor ( uint256 emissionStartTimestamp_, uint256 emissionEndTimestamp_, uint256 emissionPerDay_ ) ERC20("Mars26", "M26") { _emissionStartTimestamp = emissionStartTimestamp_; _emissionEndTimestamp = emissionEndTimestamp_; _emissionPerDay = emissionPerDay_; } function emissionStartTimestamp() public view returns (uint256) { return _emissionStartTimestamp; } function emissionEndTimestamp() public view returns (uint256) { return _emissionEndTimestamp; } function emissionPerDay() public view returns (uint256) { return _emissionPerDay; } function marsAddress() public view returns (address) { return address(_mars); } /** * @dev Sets Mars contract address. Can only be called once by owner. */ function setMarsAddress(address marsAddress_) public onlyOwner { require(address(_mars) == address(0), "Already set"); _mars = Mars(marsAddress_); } /** * @dev Returns timestamp at which accumulated M26s have last been claimed for a {tokenIndex}. */ function lastClaim(uint256 tokenIndex) public view returns (uint256) { require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : _emissionStartTimestamp; return lastClaimed; } /** * @dev Returns amount of accumulated M26s for {tokenIndex}. */ function accumulated(uint256 tokenIndex) public view returns (uint256) { require(block.timestamp > _emissionStartTimestamp, "Emission has not started yet"); require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = lastClaim(tokenIndex); // Sanity check if last claim was on or after emission end if (lastClaimed >= _emissionEndTimestamp) return 0; uint256 accumulationPeriod = block.timestamp < _emissionEndTimestamp ? block.timestamp : _emissionEndTimestamp; // Getting the min value of both uint256 totalAccumulated = accumulationPeriod .sub(lastClaimed) .mul(_emissionPerDay) .div(_SECONDS_IN_A_DAY); // If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable) if (lastClaimed == _emissionStartTimestamp) { uint256 initialAllotment = _mars.isMintedBeforeReveal(tokenIndex) == true ? INITIAL_ALLOTMENT.mul(PRE_REVEAL_MULTIPLIER) : INITIAL_ALLOTMENT; totalAccumulated = totalAccumulated.add(initialAllotment); } return totalAccumulated; } /** * @dev Claim mints M26s and supports multiple token indices at once. */ function claim(uint256[] memory tokenIndices) public returns (uint256) { require(block.timestamp > _emissionStartTimestamp, "Emission has not started yet"); uint256 totalClaimQty = 0; for (uint i = 0; i < tokenIndices.length; i++) { // Sanity check for non-minted index require(tokenIndices[i] < _mars.totalSupply(), "NFT at index has not been minted yet"); // Duplicate token index check for (uint j = i + 1; j < tokenIndices.length; j++) { require(tokenIndices[i] != tokenIndices[j], "Duplicate token index"); } uint tokenIndex = tokenIndices[i]; require(_mars.ownerOf(tokenIndex) == msg.sender, "Sender is not the owner"); uint256 claimQty = accumulated(tokenIndex); if (claimQty != 0) { totalClaimQty = totalClaimQty.add(claimQty); _lastClaim[tokenIndex] = block.timestamp; } } require(totalClaimQty != 0, "No accumulated M26"); _mint(msg.sender, totalClaimQty); increaseAllowance(address(_mars), totalClaimQty); return totalClaimQty; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title MarsStorage contract */ contract MarsStorage is Ownable { using SafeMath for uint256; // hash code: 0x12 (SHA-2) and digest length: 0x20 (32 bytes / 256 bits) bytes2 public constant MULTIHASH_PREFIX = 0x1220; // IPFS CID Version: v0 uint256 public constant CID_VERSION = 0; // IPFS v0 CIDs in hexadecimal without multihash prefix ordered by initial sequence bytes32[] private _intitialSequenceTokenHashes; uint256 internal _maxSupply; bytes internal constant _ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; /** * @dev Sets immutable values of contract. */ constructor (uint256 maxSupply_) { _maxSupply = maxSupply_; } /** * @dev Returns the IPFS v0 CID of {initialSequenceIndex}. * * The returned values can be concatenated and hashed using SHA2-256 to verify the * provenance hash. */ function initialSequenceTokenCID(uint256 initialSequenceIndex) public view returns (string memory) { bytes memory tokenCIDHex = abi.encodePacked( MULTIHASH_PREFIX, _intitialSequenceTokenHashes[initialSequenceIndex] ); string memory tokenCID = _toBase58(tokenCIDHex); return tokenCID; } /** * @dev Sets token hashes in the initially set order as verifiable through * {_provenanceHash}. * * Provided {tokenHashes} are IPFS v0 CIDs in hexadecimal without the prefix 0x1220 * and ordered in the initial sequence. */ function setInitialSequenceTokenHashes(bytes32[] memory tokenHashes) onlyOwner public { setInitialSequenceTokenHashesAtIndex(_intitialSequenceTokenHashes.length, tokenHashes); } /** * @dev Sets token hashes in the initially set order starting at {startIndex}. */ function setInitialSequenceTokenHashesAtIndex( uint256 startIndex, bytes32[] memory tokenHashes ) public onlyOwner { require(startIndex <= _intitialSequenceTokenHashes.length); for (uint256 i = 0; i < tokenHashes.length; i++) { if ((i + startIndex) >= _intitialSequenceTokenHashes.length) { _intitialSequenceTokenHashes.push(tokenHashes[i]); } else { _intitialSequenceTokenHashes[i + startIndex] = tokenHashes[i]; } } require(_intitialSequenceTokenHashes.length <= _maxSupply); } // Source: verifyIPFS (https://github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol) // @author Martin Lundfall ([email protected]) // @dev Converts hex string to base 58 function _toBase58(bytes memory source) internal pure returns (string memory) { if (source.length == 0) return new string(0); uint8[] memory digits = new uint8[](46); digits[0] = 0; uint8 digitlength = 1; for (uint256 i = 0; i < source.length; ++i) { uint256 carry = uint8(source[i]); for (uint256 j = 0; j < digitlength; ++j) { carry += uint256(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } return string(_toAlphabet(_reverse(_truncate(digits, digitlength)))); } function _truncate(uint8[] memory array, uint8 length) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](length); for (uint256 i = 0; i < length; i++) { output[i] = array[i]; } return output; } function _reverse(uint8[] memory input) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](input.length); for (uint256 i = 0; i < input.length; i++) { output[i] = input[input.length - 1 - i]; } return output; } function _toAlphabet(uint8[] memory indices) internal pure returns (bytes memory) { bytes memory output = new bytes(indices.length); for (uint256 i = 0; i < indices.length; i++) { output[i] = _ALPHABET[indices[i]]; } return output; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.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 { /** * @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 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All 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_; } /** * @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 this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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); }
Returns the set token URI, i.e. IPFS v0 CID, of {initialSequenceIndex}./ If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
function tokenURIOfInitialSequenceIndex(uint256 initialSequenceIndex) public view returns (string memory) { require(_startingIndex > 0, "Tokens have not been assigned yet"); string memory tokenCID = initialSequenceTokenCID(initialSequenceIndex); string memory base = _baseURI(); if (bytes(base).length == 0) { return tokenCID; } if (bytes(tokenCID).length > 0) { return string(abi.encodePacked(base, tokenCID)); } return base; }
7,025,237
./partial_match/5/0xc54455e1Ac910e3e4Edd7dbdb8EA46F97f806E69/sources/MISOLiquidityLauncher.sol
Single gateway to initialize the MISO Liquidity Launcher with proper address Can only be initialized once/
function initMISOLiquidityLauncher(address _accessControls, address _WETH) external { require(!initialised); initialised = true; accessControls = MISOAccessControls(_accessControls); WETH = _WETH; emit MisoInitLiquidityLauncher(msg.sender); }
16,860,346
//Address: 0x3aaa175924a77ee4b40606f714b727331e430ece //Contract name: MonsterCreatorInterface //Balance: 0 Ether //Verification Date: 1/19/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.11; contract Ownable { address public owner; /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract MonsterAccessControl { event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public adminAddress; /// @dev Access modifier for CEO-only functionality modifier onlyAdmin() { require(msg.sender == adminAddress); _; } } // This contract stores all data on the blockchain // only our other contracts can interact with this // the data here will be valid for all eternity even if other contracts get updated // this way we can make sure that our Monsters have a hard-coded value attached to them // that no one including us can change(!) contract MonstersData { address coreContract; // struct Monster { // timestamp of block when this monster was spawned/created uint64 birthTime; // generation number // gen0 is the very first generation - the later monster spawn the less likely they are to have // special attributes and stats // uint16 generation; uint16 hp; // health points uint16 attack; // attack points uint16 defense; // defense points uint16 spAttack; // special attack uint16 spDefense; // special defense uint16 speed; // speed responsible of who attacks first(!) uint16 typeOne; uint16 typeTwo; uint16 mID; // this id (from 1 to 151) is responsible for everything visually like showing the real deal! bool tradeable; //uint16 uID; // unique id // These attributes are handled by mappings since they would overflow the maximum stack //bool female // string nickname } // lv1 base stats struct MonsterBaseStats { uint16 hp; uint16 attack; uint16 defense; uint16 spAttack; uint16 spDefense; uint16 speed; } // lomonsterion struct used for travelling around the "world" // struct Area { // areaID used in-engine to determine world position // minimum level to enter this area... uint16 minLevel; } struct Trainer { // timestamp of block when this player/trainer was created uint64 birthTime; // add username string username; // current area in the "world" uint16 currArea; address owner; } // take timestamp of block this game was created on the blockchain uint64 creationBlock = uint64(now); } contract MonstersBase is MonsterAccessControl, MonstersData { /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a monster /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); bool lockedMonsterCreator = false; MonsterAuction public monsterAuction; MonsterCreatorInterface public monsterCreator; function setMonsterCreatorAddress(address _address) external onlyAdmin { // only set this once so we (the devs) can't cheat! require(!lockedMonsterCreator); MonsterCreatorInterface candidateContract = MonsterCreatorInterface(_address); monsterCreator = candidateContract; lockedMonsterCreator = true; } // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; // array containing all monsters in existence Monster[] monsters; uint8[] areas; uint8 areaIndex = 0; mapping(address => Trainer) public addressToTrainer; /// @dev A mapping from monster IDs to the address that owns them. All monster have /// some valid owner address, even gen0 monster are created with a non-zero owner. mapping (uint256 => address) public monsterIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; mapping (uint256 => address) public monsterIndexToApproved; mapping (uint256 => string) public monsterIdToNickname; mapping (uint256 => bool) public monsterIdToTradeable; mapping (uint256 => uint256) public monsterIdToGeneration; mapping (uint256 => MonsterBaseStats) public baseStats; mapping (uint256 => uint8[7]) public monsterIdToIVs; // adds new area to world function _createArea() internal { areaIndex++; areas.push(areaIndex); } function _createMonster( uint256 _generation, uint256 _hp, uint256 _attack, uint256 _defense, uint256 _spAttack, uint256 _spDefense, uint256 _speed, uint256 _typeOne, uint256 _typeTwo, address _owner, uint256 _mID, bool tradeable ) internal returns (uint) { Monster memory _monster = Monster({ birthTime: uint64(now), hp: uint16(_hp), attack: uint16(_attack), defense: uint16(_defense), spAttack: uint16(_spAttack), spDefense: uint16(_spDefense), speed: uint16(_speed), typeOne: uint16(_typeOne), typeTwo: uint16(_typeTwo), mID: uint16(_mID), tradeable: tradeable }); uint256 newMonsterId = monsters.push(_monster) - 1; monsterIdToTradeable[newMonsterId] = tradeable; monsterIdToGeneration[newMonsterId] = _generation; require(newMonsterId == uint256(uint32(newMonsterId))); monsterIdToNickname[newMonsterId] = ""; _transfer(0, _owner, newMonsterId); return newMonsterId; } function _createTrainer(string _username, uint16 _starterId, address _owner) internal returns (uint mon) { Trainer memory _trainer = Trainer({ birthTime: uint64(now), username: string(_username), currArea: uint16(1), // sets to first area!, owner: address(_owner) }); // starter stats are hardcoded! if (_starterId == 1) { uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(1)); mon = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, 1, false); } else if (_starterId == 2) { uint8[8] memory Stats2 = uint8[8](monsterCreator.getMonsterStats(4)); mon = _createMonster(0, Stats2[0], Stats2[1], Stats2[2], Stats2[3], Stats2[4], Stats2[5], Stats2[6], Stats2[7], _owner, 4, false); } else if (_starterId == 3) { uint8[8] memory Stats3 = uint8[8](monsterCreator.getMonsterStats(7)); mon = _createMonster(0, Stats3[0], Stats3[1], Stats3[2], Stats3[3], Stats3[4], Stats3[5], Stats3[6], Stats3[7], _owner, 7, false); } } function _moveToArea(uint16 _newArea, address player) internal { addressToTrainer[player].currArea = _newArea; } // assigns ownership of monster to address function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to]++; monsterIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete monsterIndexToApproved[_tokenId]; } // Emit Transfer event Transfer(_from, _to, _tokenId); } // Only admin can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyAdmin { //require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the monsters, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string) public view 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 MonsterOwnership is MonstersBase, ERC721 { string public constant name = "ChainMonsters"; string public constant symbol = "CHMO"; // The contract that will return monster metadata ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyAdmin { erc721Metadata = ERC721Metadata(_contractAddress); } function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return monsterIndexToOwner[_tokenId] == _claimant; } function _isTradeable(uint256 _tokenId) external view returns (bool) { return monsterIdToTradeable[_tokenId]; } /// @dev Checks if a given address currently has transferApproval for a particular monster. /// @param _claimant the address we are confirming monster is approved for. /// @param _tokenId monster id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return monsterIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting monsters on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { monsterIndexToApproved[_tokenId] = _approved; } function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } function transfer (address _to, uint256 _tokenId) external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any monsters (except very briefly // after a gen0 monster is created and before it goes on auction). require(_to != address(this)); // You can only send your own monster. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific monster via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the monster that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId ) external { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a monster owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the monster to be transfered. /// @param _to The address that should take ownership of the monster. Can be any address, /// including the caller. /// @param _tokenId The ID of the monster to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom (address _from, address _to, uint256 _tokenId ) external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any monsters (except very briefly // after a gen0 monster is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership //require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return monsters.length; } function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = monsterIndexToOwner[_tokenId]; require(owner != address(0)); } 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 totalMonsters = totalSupply(); uint256 resultIndex = 0; uint256 monsterId; for (monsterId = 0; monsterId <= totalMonsters; monsterId++) { if (monsterIndexToOwner[monsterId] == _owner) { result[resultIndex] = monsterId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>) /// 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 view { // 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 <[email protected]>) /// 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 view returns (string) { var 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 monster whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } contract MonsterAuctionBase { // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; ChainMonstersCore public core; struct Auction { // current owner address seller; // price in wei uint256 price; // time when auction started uint64 startedAt; uint256 id; } // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping(uint256 => Auction) tokenIdToAuction; mapping(uint256 => address) public auctionIdToSeller; mapping (address => uint256) public ownershipAuctionCount; event AuctionCreated(uint256 tokenId, uint256 price, uint256 uID, address seller); event AuctionSuccessful(uint256 tokenId, uint256 price, address newOwner, uint256 uID); event AuctionCancelled(uint256 tokenId, uint256 uID); function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.price), uint256(_auction.id), address(_auction.seller) ); } function _cancelAuction(uint256 _tokenId, address _seller) internal { Auction storage _auction = tokenIdToAuction[_tokenId]; uint256 uID = _auction.id; _removeAuction(_tokenId); ownershipAuctionCount[_seller]--; _transfer(_seller, _tokenId); AuctionCancelled(_tokenId, uID); } function _buy(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = auction.price; require(_bidAmount >= price); address seller = auction.seller; uint256 uID = auction.id; // Auction Bid looks fine! so remove _removeAuction(_tokenId); ownershipAuctionCount[seller]--; if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) if(seller != address(core)) { seller.transfer(sellerProceeds); } } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender, uID); return price; } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } contract MonsterAuction is MonsterAuctionBase, Ownable { bool public isMonsterAuction = true; uint256 public auctionIndex = 0; /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); function MonsterAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); nonFungibleContract = candidateContract; ChainMonstersCore candidateCoreContract = ChainMonstersCore(_nftAddress); core = candidateCoreContract; } // only possible to decrease ownerCut! function setOwnerCut(uint256 _cut) external onlyOwner { require(_cut <= ownerCut); ownerCut = _cut; } function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } function tokensInAuctionsOfOwner(address _owner) external view returns(uint256[] auctionTokens) { uint256 numAuctions = ownershipAuctionCount[_owner]; uint256[] memory result = new uint256[](numAuctions); uint256 totalAuctions = core.totalSupply(); uint256 resultIndex = 0; uint256 auctionId; for (auctionId = 0; auctionId <= totalAuctions; auctionId++) { Auction storage auction = tokenIdToAuction[auctionId]; if (auction.seller == _owner) { result[resultIndex] = auctionId; resultIndex++; } } return result; } function createAuction(uint256 _tokenId, uint256 _price, address _seller) external { require(_price == uint256(_price)); require(core._isTradeable(_tokenId)); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint256(_price), uint64(now), uint256(auctionIndex) ); auctionIdToSeller[auctionIndex] = _seller; ownershipAuctionCount[_seller]++; auctionIndex++; _addAuction(_tokenId, auction); } function buy(uint256 _tokenId) external payable { //delete auctionIdToSeller[_tokenId]; // buy will throw if the bid or funds transfer fails _buy (_tokenId, msg.value); _transfer(msg.sender, _tokenId); } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 price, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.price, auction.startedAt ); } function getPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return auction.price; } } contract ChainMonstersAuction is MonsterOwnership { function setMonsterAuctionAddress(address _address) external onlyAdmin { MonsterAuction candidateContract = MonsterAuction(_address); require(candidateContract.isMonsterAuction()); monsterAuction = candidateContract; } uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 5000; // Counts the number of monster the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; // its stats are completely dependent on the spawn alghorithm function createPromoMonster(uint256 _mId, address _owner) external onlyAdmin { // during generation we have to keep in mind that we have only 10,000 tokens available // which have to be divided by 151 monsters, some rarer than others // see WhitePaper for gen0/promo monster plan require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId))); uint8[7] memory IVs = uint8[7](monsterCreator.getGen0IVs()); uint256 monsterId = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, _mId, true); monsterIdToTradeable[monsterId] = true; monsterIdToIVs[monsterId] = IVs; } function createGen0Auction(uint256 _mId, uint256 price) external onlyAdmin { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId))); uint8[7] memory IVs = uint8[7](monsterCreator.getGen0IVs()); uint256 monsterId = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], this, _mId, true); monsterIdToTradeable[monsterId] = true; monsterIdToIVs[monsterId] = IVs; monsterAuction.createAuction(monsterId, price, address(this)); gen0CreatedCount++; } } // used during launch for world championship // can and will be upgraded during development with new battle system! // this is just to give players something to do and test their monsters // also demonstrates how we can build up more mechanics on top of our locked core contract! contract MonsterChampionship is Ownable { bool public isMonsterChampionship = true; ChainMonstersCore core; // list of top ten address[10] topTen; // holds the address current "world" champion address public currChampion; mapping (address => uint256) public addressToPowerlevel; mapping (uint256 => address) public rankToAddress; // try to beat every other player in the top10 with your strongest monster! // effectively looping through all top10 players, beating them one by one // and if strong enough placing your in the top10 as well function contestChampion(uint256 _tokenId) external { uint maxIndex = 9; // fail tx if player is already champion! // in theory players could increase their powerlevel by contesting themselves but // this check stops that from happening so other players have the chance to // become the temporary champion! if (currChampion == msg.sender) revert(); require(core.isTrainer(msg.sender)); require(core.monsterIndexToOwner(_tokenId) == msg.sender); uint myPowerlevel = core.getMonsterPowerLevel(_tokenId); // checks if this transaction is useless // since we can't fight against ourself! // also stops reentrancy attacks require(myPowerlevel > addressToPowerlevel[msg.sender]); uint myRank = 0; for (uint i=0; i<=maxIndex; i++) { //if (addres) if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) { // you have beaten this one so increase temporary rank myRank = i; if (myRank == maxIndex) { currChampion = msg.sender; } } } addressToPowerlevel[msg.sender] = myPowerlevel; address[10] storage newTopTen = topTen; if (currChampion == msg.sender) { for (uint j=0; j<maxIndex; j++) { // remove ourselves from this list in case if (newTopTen[j] == msg.sender) { newTopTen[j] = 0x0; break; } } } for (uint x=0; x<=myRank; x++) { if (x == myRank) { newTopTen[x] = msg.sender; } else { if (x < maxIndex) newTopTen[x] = topTen[x+1]; } } topTen = newTopTen; } function getTopPlayers() external view returns ( address[10] players ) { players = topTen; } function MonsterChampionship(address coreContract) public { core = ChainMonstersCore(coreContract); } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } } // where the not-so-much "hidden" magic happens contract MonsterCreatorInterface is Ownable { uint8 public lockedMonsterStatsCount = 0; uint nonce = 0; function rand(uint8 min, uint8 max) public returns (uint8) { nonce++; uint8 result = (uint8(sha3(block.blockhash(block.number-1), nonce ))%max); if (result < min) { result = result+min; } return result; } function shinyRand(uint16 min, uint16 max) public returns (uint16) { nonce++; uint16 result = (uint16(sha3(block.blockhash(block.number-1), nonce ))%max); if (result < min) { result = result+min; } return result; } mapping(uint256 => uint8[8]) public baseStats; function addBaseStats(uint256 _mId, uint8[8] data) external onlyOwner { // lock" the stats down forever // since hp is never going to be 0 this is a valid check // so we have to be extra careful when adding new baseStats! require(data[0] > 0); require(baseStats[_mId][0] == 0); baseStats[_mId] = data; } function _addBaseStats(uint256 _mId, uint8[8] data) internal { baseStats[_mId] = data; lockedMonsterStatsCount++; } function MonsterCreatorInterface() public { // these monsters are already down and "locked" down stats/design wise _addBaseStats(1, [45, 49, 49, 65, 65, 45, 12, 4]); _addBaseStats(2, [60, 62, 63, 80, 80, 60, 12, 4]); _addBaseStats(3, [80, 82, 83, 100, 100, 80, 12, 4]); _addBaseStats(4, [39, 52, 43, 60, 50, 65, 10, 6]); _addBaseStats(5, [58, 64, 58, 80, 65, 80, 10, 6]); _addBaseStats(6, [78, 84, 78, 109, 85, 100, 10, 6]); _addBaseStats(7, [44, 48, 65, 50, 64, 43, 11, 14]); _addBaseStats(8, [59, 63, 80, 65, 80, 58, 11, 14]); _addBaseStats(9, [79, 83, 100, 85, 105, 78, 11, 14]); _addBaseStats(10, [40, 35, 30, 20, 20, 50, 7, 4]); _addBaseStats(149, [55, 50, 45, 135, 95, 120, 8, 14]); _addBaseStats(150, [91, 134, 95, 100, 100, 80, 2, 5]); _addBaseStats(151, [100, 100, 100, 100, 100, 100, 5, 19]); } // this serves as a lookup for new monsters to be generated since all monsters // of the same id share the base stats function getMonsterStats( uint256 _mID) external constant returns(uint8[8] stats) { stats[0] = baseStats[_mID][0]; stats[1] = baseStats[_mID][1]; stats[2] = baseStats[_mID][2]; stats[3] = baseStats[_mID][3]; stats[4] = baseStats[_mID][4]; stats[5] = baseStats[_mID][5]; stats[6] = baseStats[_mID][6]; stats[7] = baseStats[_mID][7]; } // generates randomized IVs for a new monster function getMonsterIVs() external returns(uint8[7] ivs) { bool shiny = false; uint16 chance = shinyRand(1, 8192); if (chance == 42) { shiny = true; } // IVs range between 0 and 31 // stat range modified for shiny monsters! if (shiny == true) { ivs[0] = uint8(rand(10, 31)); ivs[1] = uint8(rand(10, 31)); ivs[2] = uint8(rand(10, 31)); ivs[3] = uint8(rand(10, 31)); ivs[4] = uint8(rand(10, 31)); ivs[5] = uint8(rand(10, 31)); ivs[6] = 1; } else { ivs[0] = uint8(rand(0, 31)); ivs[1] = uint8(rand(0, 31)); ivs[2] = uint8(rand(0, 31)); ivs[3] = uint8(rand(0, 31)); ivs[4] = uint8(rand(0, 31)); ivs[5] = uint8(rand(0, 31)); ivs[6] = 0; } } // gen0 monsters profit from shiny boost while shiny gen0s have potentially even higher IVs! // further increasing the rarity by also doubling the shiny chance! function getGen0IVs() external returns (uint8[7] ivs) { bool shiny = false; uint16 chance = shinyRand(1, 4096); if (chance == 42) { shiny = true; } if (shiny) { ivs[0] = uint8(rand(15, 31)); ivs[1] = uint8(rand(15, 31)); ivs[2] = uint8(rand(15, 31)); ivs[3] = uint8(rand(15, 31)); ivs[4] = uint8(rand(15, 31)); ivs[5] = uint8(rand(15, 31)); ivs[6] = 1; } else { ivs[0] = uint8(rand(10, 31)); ivs[1] = uint8(rand(10, 31)); ivs[2] = uint8(rand(10, 31)); ivs[3] = uint8(rand(10, 31)); ivs[4] = uint8(rand(10, 31)); ivs[5] = uint8(rand(10, 31)); ivs[6] = 0; } } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } } contract GameLogicContract { bool public isGameLogicContract = true; function GameLogicContract() public { } } contract ChainMonstersCore is ChainMonstersAuction, Ownable { // using a bool to enable us to prepare the game bool hasLaunched = false; // this address will hold future gamelogic in place address gameContract; function ChainMonstersCore() public { adminAddress = msg.sender; _createArea(); // area 1 _createArea(); // area 2 } // we don't know the exact interfaces yet so use the lockedMonsterStats value to determine if the game is "ready" // see WhitePaper for explaination for our upgrade and development roadmap function setGameLogicContract(address _candidateContract) external onlyOwner { require(monsterCreator.lockedMonsterStatsCount() == 151); require(GameLogicContract(_candidateContract).isGameLogicContract()); gameContract = _candidateContract; } // only callable by gameContract after the full game is launched // since all additional monsters after the promo/gen0 ones need to use this coreContract // contract as well we have to prepare this core for our future updates where // players can freely roam the world and hunt ChainMonsters thus generating more function spawnMonster(uint256 _mId, address _owner) external { require(msg.sender == gameContract); uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId))); uint8[7] memory IVs = uint8[7](monsterCreator.getMonsterIVs()); // important to note that the IV generators do not use Gen0 methods and are Generation 1 // this means there won't be more than the 10,000 Gen0 monsters sold during the development through the marketplace uint256 monsterId = _createMonster(1, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, _mId, true); monsterIdToTradeable[monsterId] = true; monsterIdToIVs[monsterId] = IVs; } // used to add playable content to the game // monsters will only spawn in certain areas so some are locked on release // due to the game being in active development on "launch" // each monster has a maximum number of 3 areas where it can appear // function createArea() public onlyAdmin { _createArea(); } function createTrainer(string _username, uint16 _starterId) public { require(hasLaunched); // only one trainer/account per ethereum address require(addressToTrainer[msg.sender].owner == 0); // valid input check require(_starterId == 1 || _starterId == 2 || _starterId == 3 ); uint256 mon = _createTrainer(_username, _starterId, msg.sender); // due to stack limitations we have to assign the IVs here: uint8[7] memory IVs = uint8[7](monsterCreator.getMonsterIVs()); monsterIdToIVs[mon] = IVs; } function changeUsername(string _name) public { require(addressToTrainer[msg.sender].owner == msg.sender); addressToTrainer[msg.sender].username = _name; } function changeMonsterNickname(uint256 _tokenId, string _name) public { // users won't be able to rename a monster that is part of an auction require(_owns(msg.sender, _tokenId)); // some string checks...? monsterIdToNickname[_tokenId] = _name; } function moveToArea(uint16 _newArea) public { // never allow anyone to move to area 0 or below since this is used // to determine if a trainer profile exists in another method! require(_newArea > 0); // make sure that this area exists yet! require(areas.length >= _newArea); // when player is not stuck doing something else he can move freely! _moveToArea(_newArea, msg.sender); } // to be changed to retrieve current stats! function getMonster(uint256 _id) external view returns ( uint256 birthTime, uint256 generation, uint256 hp, uint256 attack, uint256 defense, uint256 spAttack, uint256 spDefense, uint256 speed, uint256 typeOne, uint256 typeTwo, uint256 mID, bool tradeable, uint256 uID ) { Monster storage mon = monsters[_id]; birthTime = uint256(mon.birthTime); generation = 0; // hardcoding due to stack too deep error hp = uint256(mon.hp); attack = uint256(mon.attack); defense = uint256(mon.defense); spAttack = uint256(mon.spAttack); spDefense = uint256(mon.spDefense); speed = uint256(mon.speed); typeOne = uint256(mon.typeOne); typeTwo = uint256(mon.typeTwo); mID = uint256(mon.mID); tradeable = bool(mon.tradeable); // hack to overcome solidity's stack limitation in monster struct.... uID = _id; } // this method only returns the "base" powerlevel of a monster which will be used // in more advanced fighting calculations later on function getMonsterPowerLevel(uint256 _tokenId) external view returns ( uint256 powerlevel ) { Monster storage mon = monsters[_tokenId]; uint8[7] storage IVs = monsterIdToIVs[_tokenId]; powerlevel = mon.hp + IVs[0] + mon.attack + IVs[1] + mon.defense + IVs[2] + mon.spAttack + IVs[3] + mon.spDefense + IVs[4] + mon.speed + IVs[5]; } function isTrainer(address _check) external view returns ( bool isTrainer ) { Trainer storage trainer = addressToTrainer[_check]; if (trainer.currArea > 0) return true; else return false; } function withdrawBalance() external onlyOwner { uint256 balance = this.balance; owner.transfer(balance); } // after we have setup everything we can unlock the game // for public function launchGame() external onlyOwner { hasLaunched = true; } }
users won't be able to rename a monster that is part of an auction some string checks...?
function changeMonsterNickname(uint256 _tokenId, string _name) public { require(_owns(msg.sender, _tokenId)); monsterIdToNickname[_tokenId] = _name; }
932,342
/** *Submitted for verification at Etherscan.io on 2022-04-19 */ /** https://t.me/peacawk https://twitter.com/PeacawkETH */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract PEACAWK is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 7200 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 5 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("PEACAWK", "PEACAWK") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 1; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 1; uint256 _sellDevFee = 0; uint256 totalSupply = 6 * 1e6 * 1e18; maxTransactionAmount = totalSupply * 9 / 1000; // 0.9% maxTransactionAmountTxn maxWallet = totalSupply * 15 / 1000; // 1.5% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("PEACAWK", "PEACAWK") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 1; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 1; uint256 _sellDevFee = 0; uint256 totalSupply = 6 * 1e6 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
10,889,446
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; /** __ __ __________ _____ _____.__ _________ / \ / \ ____ ____\______ \_____ _/ ____\/ ____\ | ____ / _____/ ___________ \ \/\/ // __ \ / \| _/\__ \\ __\\ __\| | _/ __ \ \_____ \_/ __ \_ __ \ \ /\ ___/| | \ | \ / __ \| | | | | |_\ ___/ / \ ___/| | \/ \__/\ / \___ >___| /____|_ /(____ /__| |__| |____/\___ >_______ /\___ >__| \/ \/ \/ \/ \/ \/ \/ \/ */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./ERC721A.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /// @title An ERC721A minting contract for WenRaffleSer NFTs contract WRSContractV7 is ERC721A, Ownable, Pausable, ReentrancyGuard { using ECDSA for bytes32; uint public constant MAX_SUPPLY = 3993; uint public constant PRICE = 0.05 ether; uint public constant MAX_PER_MINT = 5; uint public constant MAX_PER_WALLET = 10; uint public constant MAX_MINT_DURING_WHITELIST = 2023; uint public constant MAX_PER_WHITELISTED_WALLET = 3; uint public constant MAX_MINTS_BY_OWNER = 23; uint public WHITELIST_START_TIME = 1651593600; uint public WHITELIST_END_TIME = WHITELIST_START_TIME + 360 minutes; uint public currentWhitelistMints; uint public ownerCurrentMints; address public multisigWallet = 0xBBF6DbdD752841478ABff02C685A8cb20c344221; string public baseURI="https://gateway.pinata.cloud/ipfs/Qmb3ybcQxQEy5jomtLYirXVRHYmG57xvLJLszPqGK3sNRW"; bool public isPublicMintStarted; mapping(address=>uint) public addressToMints; constructor() ERC721A("WenRaffleSer", "WRS") { _pause(); } /// @notice mints allowed only by the owner function ownerMint(uint256 _quantity) external whenNotPaused onlyOwner { require(ownerCurrentMints + _quantity <= MAX_MINTS_BY_OWNER,"Limit exceeding"); require(totalSupply() + _quantity <= MAX_SUPPLY, "Not enough NFTs left to mint"); ownerCurrentMints = ownerCurrentMints + _quantity; currentWhitelistMints=currentWhitelistMints+_quantity; _safeMint(msg.sender, _quantity); } /// @notice only owner can start the public mint function startPublicMint() external whenNotPaused onlyOwner{ isPublicMintStarted=true; } /// @notice mints allowed only by the whitelisted addresses with signature function whitelistMint(uint256 _quantity, bytes memory _signature) external payable whenNotPaused nonReentrant { require(block.timestamp >= WHITELIST_START_TIME, "Whitelist sale has'nt yet started"); require(addressToMints[msg.sender]+ _quantity<=MAX_PER_WHITELISTED_WALLET,"Max mints reached"); require(block.timestamp <= WHITELIST_END_TIME, "Whitelist sale has ended"); require(_quantity <= MAX_PER_MINT, "Can mint at max 5 in each batch"); require(currentWhitelistMints+_quantity<=MAX_MINT_DURING_WHITELIST,"Whitelist minting quota exceeded"); require(isMessageValid(owner(),_signature), "Invalid signature"); require(totalSupply() + _quantity <= MAX_SUPPLY, "Not enough NFTs left to mint"); require(PRICE * _quantity <= msg.value, "Insufficient funds sent"); require(balanceOf(msg.sender) + _quantity <= MAX_PER_WHITELISTED_WALLET, "Max limit per wallet reached"); addressToMints[msg.sender]=addressToMints[msg.sender]+_quantity; currentWhitelistMints=currentWhitelistMints+_quantity; _safeMint(msg.sender, _quantity); } /// @notice mint open to public function mint(uint256 _quantity) external payable whenNotPaused nonReentrant { require(isPublicMintStarted, "Public mint has'nt yet started"); require(_quantity <= MAX_PER_MINT, "Can mint at max 5 in each batch"); require(addressToMints[msg.sender]+ _quantity<=MAX_PER_WALLET,"Max mints reached"); require(totalSupply() + _quantity <= MAX_SUPPLY, "Not enough NFTs left to mint"); require(PRICE * _quantity <= msg.value, "Insufficient funds sent"); require(balanceOf(msg.sender) + _quantity <= MAX_PER_WALLET, "Max limit per wallet reached"); addressToMints[msg.sender]=addressToMints[msg.sender]+_quantity; _safeMint(msg.sender, _quantity); } /// @return array of tokens owned by the specified parameter address function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 count = balanceOf(_owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(_owner, i); } return ids; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token."); return _baseURI(); } function setWhitelistStartTime(uint _time) external whenNotPaused onlyOwner{ WHITELIST_START_TIME=_time; WHITELIST_END_TIME = WHITELIST_START_TIME + 360 minutes; } function tokenOfOwnerByIndex(address _owner, uint256 _index) internal view returns (uint256) { require(_index < balanceOf(_owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; unchecked { for (uint256 i; 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'); } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function isMessageValid(address _owner,bytes memory _signature) internal view returns (bool) { bytes32 messagehash = keccak256( abi.encodePacked(address(this), msg.sender) ); address signer = messagehash.toEthSignedMessageHash().recover( _signature ); if (_owner == signer) { return true; } else { return false; } } /// @notice only owner can withdraw the money function withdrawMoney() external onlyOwner nonReentrant { (bool success, ) = multisigWallet.call{value: address(this).balance}(""); require(success, "Transfer failed."); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/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 // Creator: Chiru Labs pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); 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 _startTokenId() (defaults to 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; // 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_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { 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) { 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) { 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 { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @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 virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ 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 { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev 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) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // 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; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.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; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // 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 storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.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; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // 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 (last updated v4.6.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * 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; /** * @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 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 the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../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 // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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); }
mints allowed only by the whitelisted addresses with signature
function whitelistMint(uint256 _quantity, bytes memory _signature) external payable whenNotPaused nonReentrant { require(block.timestamp >= WHITELIST_START_TIME, "Whitelist sale has'nt yet started"); require(addressToMints[msg.sender]+ _quantity<=MAX_PER_WHITELISTED_WALLET,"Max mints reached"); require(block.timestamp <= WHITELIST_END_TIME, "Whitelist sale has ended"); require(_quantity <= MAX_PER_MINT, "Can mint at max 5 in each batch"); require(currentWhitelistMints+_quantity<=MAX_MINT_DURING_WHITELIST,"Whitelist minting quota exceeded"); require(isMessageValid(owner(),_signature), "Invalid signature"); require(totalSupply() + _quantity <= MAX_SUPPLY, "Not enough NFTs left to mint"); require(PRICE * _quantity <= msg.value, "Insufficient funds sent"); require(balanceOf(msg.sender) + _quantity <= MAX_PER_WHITELISTED_WALLET, "Max limit per wallet reached"); addressToMints[msg.sender]=addressToMints[msg.sender]+_quantity; currentWhitelistMints=currentWhitelistMints+_quantity; _safeMint(msg.sender, _quantity); }
14,836,948
//Address: 0x2c1bf16a6ab64c2d55d916ba928138e488d3785a //Contract name: XRTToken //Balance: 0 Ether //Verification Date: 2/9/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.19; contract Token { function totalSupply() public constant returns (uint256 supply) {} function balanceOf(address _owner) public constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) public returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {} function approve(address _spender, uint256 _value) public returns (bool success) {} function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Owned{ address public owner; function Owned(){ owner = msg.sender; } modifier onlyOwner{ require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;} contract StandardToken is Token { //Internal transfer, only can be called by this contract function _transfer(address _from, address _to,uint256 _value) internal { //prevent transfer to 0x0 address. require(_to != 0x0); //check if sender has enough tokens require(balances[_from] >= _value); //check for overflows require(balances[_to] + _value > balances[_to]); uint256 previousBalances = balances[_from]+balances[_to]; //subtract value from sender balances[_from] -= _value; //add value to receiver balances[_to] += _value; Transfer(_from,_to,_value); //Assert are used for analysing statically if bugs resides assert(balances[_from] + balances[_to] == previousBalances); } function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). _transfer(msg.sender,_to,_value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] -= _value; _transfer(_from,_to,_value); return true; } //Return balance of the owner function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } //Approve the spender ammount //set allowance for other address // allows _spender to spend no more than _value tokens on your behalf function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } /**************************************/ /*INTRODUCING ADVANCE FUNCTIONALITIES*/ /*************************************/ contract XRTStandards is Owned,StandardToken { //generate a public event on the blockchain function _transfer(address _from, address _to,uint256 _value) internal { //prevent transfer to 0x0 address. require(_to != 0x0); //check if sender has enough tokens require(balances[_from] >= _value); //check for overflows require(balances[_to] + _value > balances[_to]); //subtract value from sender balances[_from] -= _value; //add value to receiver balances[_to] += _value; Transfer(_from,_to,_value); } } contract XRTToken is XRTStandards { uint256 public initialSupply; string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function XRTToken(uint256 _initialSupply, string t_name, string t_symbol,string t_version, uint8 decimalsUnits,uint256 OneEthValue) public { initialSupply = _initialSupply; decimals = decimalsUnits; // Amount of decimals for display purposes (CHANGE THIS) totalSupply = initialSupply*10**uint256(decimals); // Update total supply (1000 for example) (CHANGE THIS) balances[msg.sender] = totalSupply; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) name = t_name; // Set the name for display purposes (CHANGE THIS) symbol = t_symbol; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = OneEthValue*10**uint256(decimals); fundsWallet = msg.sender; version = t_version; } function() payable{ if (msg.value == 0) { return; } totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(approve(_spender,_value)){ require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } }
generate a public event on the blockchain
{ function _transfer(address _from, address _to,uint256 _value) internal { require(_to != 0x0); require(balances[_from] >= _value); require(balances[_to] + _value > balances[_to]); balances[_from] -= _value; balances[_to] += _value; Transfer(_from,_to,_value); } }
6,427,802
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../upgrades/GraphUpgradeable.sol"; import "../utils/TokenUtils.sol"; import "./IStaking.sol"; import "./StakingStorage.sol"; import "./libs/MathUtils.sol"; import "./libs/Rebates.sol"; import "./libs/Stakes.sol"; /** * @title Staking contract */ contract Staking is StakingV2Storage, GraphUpgradeable, IStaking { using SafeMath for uint256; using Stakes for Stakes.Indexer; using Rebates for Rebates.Pool; // 100% in parts per million uint32 private constant MAX_PPM = 1000000; // -- Events -- /** * @dev Emitted when `indexer` update the delegation parameters for its delegation pool. */ event DelegationParametersUpdated( address indexed indexer, uint32 indexingRewardCut, uint32 queryFeeCut, uint32 cooldownBlocks ); /** * @dev Emitted when `indexer` stake `tokens` amount. */ event StakeDeposited(address indexed indexer, uint256 tokens); /** * @dev Emitted when `indexer` unstaked and locked `tokens` amount `until` block. */ event StakeLocked(address indexed indexer, uint256 tokens, uint256 until); /** * @dev Emitted when `indexer` withdrew `tokens` staked. */ event StakeWithdrawn(address indexed indexer, uint256 tokens); /** * @dev Emitted when `indexer` was slashed for a total of `tokens` amount. * Tracks `reward` amount of tokens given to `beneficiary`. */ event StakeSlashed( address indexed indexer, uint256 tokens, uint256 reward, address beneficiary ); /** * @dev Emitted when `delegator` delegated `tokens` to the `indexer`, the delegator * gets `shares` for the delegation pool proportionally to the tokens staked. */ event StakeDelegated( address indexed indexer, address indexed delegator, uint256 tokens, uint256 shares ); /** * @dev Emitted when `delegator` undelegated `tokens` from `indexer`. * Tokens get locked for withdrawal after a period of time. */ event StakeDelegatedLocked( address indexed indexer, address indexed delegator, uint256 tokens, uint256 shares, uint256 until ); /** * @dev Emitted when `delegator` withdrew delegated `tokens` from `indexer`. */ event StakeDelegatedWithdrawn( address indexed indexer, address indexed delegator, uint256 tokens ); /** * @dev Emitted when `indexer` allocated `tokens` amount to `subgraphDeploymentID` * during `epoch`. * `allocationID` indexer derived address used to identify the allocation. * `metadata` additional information related to the allocation. */ event AllocationCreated( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address indexed allocationID, bytes32 metadata ); /** * @dev Emitted when `indexer` collected `tokens` amount in `epoch` for `allocationID`. * These funds are related to `subgraphDeploymentID`. * The `from` value is the sender of the collected funds. */ event AllocationCollected( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address indexed allocationID, address from, uint256 curationFees, uint256 rebateFees ); /** * @dev Emitted when `indexer` close an allocation in `epoch` for `allocationID`. * An amount of `tokens` get unallocated from `subgraphDeploymentID`. * The `effectiveAllocation` are the tokens allocated from creation to closing. * This event also emits the POI (proof of indexing) submitted by the indexer. * `isDelegator` is true if the sender was one of the indexer's delegators. */ event AllocationClosed( address indexed indexer, bytes32 indexed subgraphDeploymentID, uint256 epoch, uint256 tokens, address indexed allocationID, uint256 effectiveAllocation, address sender, bytes32 poi, bool isDelegator ); /** * @dev Emitted when `indexer` claimed a rebate on `subgraphDeploymentID` during `epoch` * related to the `forEpoch` rebate pool. * The rebate is for `tokens` amount and `unclaimedAllocationsCount` are left for claim * in the rebate pool. `delegationFees` collected and sent to delegation pool. */ event RebateClaimed( address indexed indexer, bytes32 indexed subgraphDeploymentID, address indexed allocationID, uint256 epoch, uint256 forEpoch, uint256 tokens, uint256 unclaimedAllocationsCount, uint256 delegationFees ); /** * @dev Emitted when `caller` set `slasher` address as `allowed` to slash stakes. */ event SlasherUpdate(address indexed caller, address indexed slasher, bool allowed); /** * @dev Emitted when `caller` set `assetHolder` address as `allowed` to send funds * to staking contract. */ event AssetHolderUpdate(address indexed caller, address indexed assetHolder, bool allowed); /** * @dev Emitted when `indexer` set `operator` access. */ event SetOperator(address indexed indexer, address indexed operator, bool allowed); /** * @dev Emitted when `indexer` set an address to receive rewards. */ event SetRewardsDestination(address indexed indexer, address indexed destination); /** * @dev Check if the caller is the slasher. */ modifier onlySlasher { require(slashers[msg.sender] == true, "!slasher"); _; } /** * @dev Check if the caller is authorized (indexer or operator) */ function _isAuth(address _indexer) private view returns (bool) { return msg.sender == _indexer || isOperator(msg.sender, _indexer) == true; } /** * @dev Initialize this contract. */ function initialize( address _controller, uint256 _minimumIndexerStake, uint32 _thawingPeriod, uint32 _protocolPercentage, uint32 _curationPercentage, uint32 _channelDisputeEpochs, uint32 _maxAllocationEpochs, uint32 _delegationUnbondingPeriod, uint32 _delegationRatio, uint32 _rebateAlphaNumerator, uint32 _rebateAlphaDenominator ) external onlyImpl { Managed._initialize(_controller); // Settings _setMinimumIndexerStake(_minimumIndexerStake); _setThawingPeriod(_thawingPeriod); _setProtocolPercentage(_protocolPercentage); _setCurationPercentage(_curationPercentage); _setChannelDisputeEpochs(_channelDisputeEpochs); _setMaxAllocationEpochs(_maxAllocationEpochs); _setDelegationUnbondingPeriod(_delegationUnbondingPeriod); _setDelegationRatio(_delegationRatio); _setDelegationParametersCooldown(0); _setDelegationTaxPercentage(0); _setRebateRatio(_rebateAlphaNumerator, _rebateAlphaDenominator); } /** * @dev Set the minimum indexer stake required to. * @param _minimumIndexerStake Minimum indexer stake */ function setMinimumIndexerStake(uint256 _minimumIndexerStake) external override onlyGovernor { _setMinimumIndexerStake(_minimumIndexerStake); } /** * @dev Internal: Set the minimum indexer stake required. * @param _minimumIndexerStake Minimum indexer stake */ function _setMinimumIndexerStake(uint256 _minimumIndexerStake) private { require(_minimumIndexerStake > 0, "!minimumIndexerStake"); minimumIndexerStake = _minimumIndexerStake; emit ParameterUpdated("minimumIndexerStake"); } /** * @dev Set the thawing period for unstaking. * @param _thawingPeriod Period in blocks to wait for token withdrawals after unstaking */ function setThawingPeriod(uint32 _thawingPeriod) external override onlyGovernor { _setThawingPeriod(_thawingPeriod); } /** * @dev Internal: Set the thawing period for unstaking. * @param _thawingPeriod Period in blocks to wait for token withdrawals after unstaking */ function _setThawingPeriod(uint32 _thawingPeriod) private { require(_thawingPeriod > 0, "!thawingPeriod"); thawingPeriod = _thawingPeriod; emit ParameterUpdated("thawingPeriod"); } /** * @dev Set the curation percentage of query fees sent to curators. * @param _percentage Percentage of query fees sent to curators */ function setCurationPercentage(uint32 _percentage) external override onlyGovernor { _setCurationPercentage(_percentage); } /** * @dev Internal: Set the curation percentage of query fees sent to curators. * @param _percentage Percentage of query fees sent to curators */ function _setCurationPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, ">percentage"); curationPercentage = _percentage; emit ParameterUpdated("curationPercentage"); } /** * @dev Set a protocol percentage to burn when collecting query fees. * @param _percentage Percentage of query fees to burn as protocol fee */ function setProtocolPercentage(uint32 _percentage) external override onlyGovernor { _setProtocolPercentage(_percentage); } /** * @dev Internal: Set a protocol percentage to burn when collecting query fees. * @param _percentage Percentage of query fees to burn as protocol fee */ function _setProtocolPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, ">percentage"); protocolPercentage = _percentage; emit ParameterUpdated("protocolPercentage"); } /** * @dev Set the period in epochs that need to pass before fees in rebate pool can be claimed. * @param _channelDisputeEpochs Period in epochs */ function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external override onlyGovernor { _setChannelDisputeEpochs(_channelDisputeEpochs); } /** * @dev Internal: Set the period in epochs that need to pass before fees in rebate pool can be claimed. * @param _channelDisputeEpochs Period in epochs */ function _setChannelDisputeEpochs(uint32 _channelDisputeEpochs) private { require(_channelDisputeEpochs > 0, "!channelDisputeEpochs"); channelDisputeEpochs = _channelDisputeEpochs; emit ParameterUpdated("channelDisputeEpochs"); } /** * @dev Set the max time allowed for indexers stake on allocations. * @param _maxAllocationEpochs Allocation duration limit in epochs */ function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external override onlyGovernor { _setMaxAllocationEpochs(_maxAllocationEpochs); } /** * @dev Internal: Set the max time allowed for indexers stake on allocations. * @param _maxAllocationEpochs Allocation duration limit in epochs */ function _setMaxAllocationEpochs(uint32 _maxAllocationEpochs) private { maxAllocationEpochs = _maxAllocationEpochs; emit ParameterUpdated("maxAllocationEpochs"); } /** * @dev Set the rebate ratio (fees to allocated stake). * @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function * @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function */ function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external override onlyGovernor { _setRebateRatio(_alphaNumerator, _alphaDenominator); } /** * @dev Set the rebate ratio (fees to allocated stake). * @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function * @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function */ function _setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) private { require(_alphaNumerator > 0 && _alphaDenominator > 0, "!alpha"); alphaNumerator = _alphaNumerator; alphaDenominator = _alphaDenominator; emit ParameterUpdated("rebateRatio"); } /** * @dev Set the delegation ratio. * If set to 10 it means the indexer can use up to 10x the indexer staked amount * from their delegated tokens * @param _delegationRatio Delegation capacity multiplier */ function setDelegationRatio(uint32 _delegationRatio) external override onlyGovernor { _setDelegationRatio(_delegationRatio); } /** * @dev Internal: Set the delegation ratio. * If set to 10 it means the indexer can use up to 10x the indexer staked amount * from their delegated tokens * @param _delegationRatio Delegation capacity multiplier */ function _setDelegationRatio(uint32 _delegationRatio) private { delegationRatio = _delegationRatio; emit ParameterUpdated("delegationRatio"); } /** * @dev Set the delegation parameters for the caller. * @param _indexingRewardCut Percentage of indexing rewards left for delegators * @param _queryFeeCut Percentage of query fees left for delegators * @param _cooldownBlocks Period that need to pass to update delegation parameters */ function setDelegationParameters( uint32 _indexingRewardCut, uint32 _queryFeeCut, uint32 _cooldownBlocks ) public override { _setDelegationParameters(msg.sender, _indexingRewardCut, _queryFeeCut, _cooldownBlocks); } /** * @dev Set the delegation parameters for a particular indexer. * @param _indexer Indexer to set delegation parameters * @param _indexingRewardCut Percentage of indexing rewards left for delegators * @param _queryFeeCut Percentage of query fees left for delegators * @param _cooldownBlocks Period that need to pass to update delegation parameters */ function _setDelegationParameters( address _indexer, uint32 _indexingRewardCut, uint32 _queryFeeCut, uint32 _cooldownBlocks ) private { // Incentives must be within bounds require(_queryFeeCut <= MAX_PPM, ">queryFeeCut"); require(_indexingRewardCut <= MAX_PPM, ">indexingRewardCut"); // Cooldown period set by indexer cannot be below protocol global setting require(_cooldownBlocks >= delegationParametersCooldown, "<cooldown"); // Verify the cooldown period passed DelegationPool storage pool = delegationPools[_indexer]; require( pool.updatedAtBlock == 0 || pool.updatedAtBlock.add(uint256(pool.cooldownBlocks)) <= block.number, "!cooldown" ); // Update delegation params pool.indexingRewardCut = _indexingRewardCut; pool.queryFeeCut = _queryFeeCut; pool.cooldownBlocks = _cooldownBlocks; pool.updatedAtBlock = block.number; emit DelegationParametersUpdated( _indexer, _indexingRewardCut, _queryFeeCut, _cooldownBlocks ); } /** * @dev Set the time in blocks an indexer needs to wait to change delegation parameters. * @param _blocks Number of blocks to set the delegation parameters cooldown period */ function setDelegationParametersCooldown(uint32 _blocks) external override onlyGovernor { _setDelegationParametersCooldown(_blocks); } /** * @dev Internal: Set the time in blocks an indexer needs to wait to change delegation parameters. * @param _blocks Number of blocks to set the delegation parameters cooldown period */ function _setDelegationParametersCooldown(uint32 _blocks) private { delegationParametersCooldown = _blocks; emit ParameterUpdated("delegationParametersCooldown"); } /** * @dev Set the period for undelegation of stake from indexer. * @param _delegationUnbondingPeriod Period in epochs to wait for token withdrawals after undelegating */ function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external override onlyGovernor { _setDelegationUnbondingPeriod(_delegationUnbondingPeriod); } /** * @dev Internal: Set the period for undelegation of stake from indexer. * @param _delegationUnbondingPeriod Period in epochs to wait for token withdrawals after undelegating */ function _setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) private { require(_delegationUnbondingPeriod > 0, "!delegationUnbondingPeriod"); delegationUnbondingPeriod = _delegationUnbondingPeriod; emit ParameterUpdated("delegationUnbondingPeriod"); } /** * @dev Set a delegation tax percentage to burn when delegated funds are deposited. * @param _percentage Percentage of delegated tokens to burn as delegation tax */ function setDelegationTaxPercentage(uint32 _percentage) external override onlyGovernor { _setDelegationTaxPercentage(_percentage); } /** * @dev Internal: Set a delegation tax percentage to burn when delegated funds are deposited. * @param _percentage Percentage of delegated tokens to burn as delegation tax */ function _setDelegationTaxPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, ">percentage"); delegationTaxPercentage = _percentage; emit ParameterUpdated("delegationTaxPercentage"); } /** * @dev Set or unset an address as allowed slasher. * @param _slasher Address of the party allowed to slash indexers * @param _allowed True if slasher is allowed */ function setSlasher(address _slasher, bool _allowed) external override onlyGovernor { require(_slasher != address(0), "!slasher"); slashers[_slasher] = _allowed; emit SlasherUpdate(msg.sender, _slasher, _allowed); } /** * @dev Set an address as allowed asset holder. * @param _assetHolder Address of allowed source for state channel funds * @param _allowed True if asset holder is allowed */ function setAssetHolder(address _assetHolder, bool _allowed) external override onlyGovernor { require(_assetHolder != address(0), "!assetHolder"); assetHolders[_assetHolder] = _allowed; emit AssetHolderUpdate(msg.sender, _assetHolder, _allowed); } /** * @dev Return if allocationID is used. * @param _allocationID Address used as signer by the indexer for an allocation * @return True if allocationID already used */ function isAllocation(address _allocationID) external view override returns (bool) { return _getAllocationState(_allocationID) != AllocationState.Null; } /** * @dev Getter that returns if an indexer has any stake. * @param _indexer Address of the indexer * @return True if indexer has staked tokens */ function hasStake(address _indexer) external view override returns (bool) { return stakes[_indexer].tokensStaked > 0; } /** * @dev Return the allocation by ID. * @param _allocationID Address used as allocation identifier * @return Allocation data */ function getAllocation(address _allocationID) external view override returns (Allocation memory) { return allocations[_allocationID]; } /** * @dev Return the current state of an allocation. * @param _allocationID Address used as the allocation identifier * @return AllocationState */ function getAllocationState(address _allocationID) external view override returns (AllocationState) { return _getAllocationState(_allocationID); } /** * @dev Return the total amount of tokens allocated to subgraph. * @param _subgraphDeploymentID Address used as the allocation identifier * @return Total tokens allocated to subgraph */ function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID) external view override returns (uint256) { return subgraphAllocations[_subgraphDeploymentID]; } /** * @dev Return the delegation from a delegator to an indexer. * @param _indexer Address of the indexer where funds have been delegated * @param _delegator Address of the delegator * @return Delegation data */ function getDelegation(address _indexer, address _delegator) external view override returns (Delegation memory) { return delegationPools[_indexer].delegators[_delegator]; } /** * @dev Return whether the delegator has delegated to the indexer. * @param _indexer Address of the indexer where funds have been delegated * @param _delegator Address of the delegator * @return True if delegator of indexer */ function isDelegator(address _indexer, address _delegator) public view override returns (bool) { return delegationPools[_indexer].delegators[_delegator].shares > 0; } /** * @dev Get the total amount of tokens staked by the indexer. * @param _indexer Address of the indexer * @return Amount of tokens staked by the indexer */ function getIndexerStakedTokens(address _indexer) external view override returns (uint256) { return stakes[_indexer].tokensStaked; } /** * @dev Get the total amount of tokens available to use in allocations. * This considers the indexer stake and delegated tokens according to delegation ratio * @param _indexer Address of the indexer * @return Amount of tokens staked by the indexer */ function getIndexerCapacity(address _indexer) public view override returns (uint256) { Stakes.Indexer memory indexerStake = stakes[_indexer]; uint256 tokensDelegated = delegationPools[_indexer].tokens; uint256 tokensDelegatedCap = indexerStake.tokensSecureStake().mul(uint256(delegationRatio)); uint256 tokensDelegatedCapacity = MathUtils.min(tokensDelegated, tokensDelegatedCap); return indexerStake.tokensAvailableWithDelegation(tokensDelegatedCapacity); } /** * @dev Returns amount of delegated tokens ready to be withdrawn after unbonding period. * @param _delegation Delegation of tokens from delegator to indexer * @return Amount of tokens to withdraw */ function getWithdraweableDelegatedTokens(Delegation memory _delegation) public view returns (uint256) { // There must be locked tokens and period passed uint256 currentEpoch = epochManager().currentEpoch(); if (_delegation.tokensLockedUntil > 0 && currentEpoch >= _delegation.tokensLockedUntil) { return _delegation.tokensLocked; } return 0; } /** * @dev Authorize or unauthorize an address to be an operator. * @param _operator Address to authorize * @param _allowed Whether authorized or not */ function setOperator(address _operator, bool _allowed) external override { require(_operator != msg.sender, "operator == sender"); operatorAuth[msg.sender][_operator] = _allowed; emit SetOperator(msg.sender, _operator, _allowed); } /** * @dev Return true if operator is allowed for indexer. * @param _operator Address of the operator * @param _indexer Address of the indexer */ function isOperator(address _operator, address _indexer) public view override returns (bool) { return operatorAuth[_indexer][_operator]; } /** * @dev Deposit tokens on the indexer stake. * @param _tokens Amount of tokens to stake */ function stake(uint256 _tokens) external override { stakeTo(msg.sender, _tokens); } /** * @dev Deposit tokens on the indexer stake. * @param _indexer Address of the indexer * @param _tokens Amount of tokens to stake */ function stakeTo(address _indexer, uint256 _tokens) public override notPartialPaused { require(_tokens > 0, "!tokens"); // Ensure minimum stake require( stakes[_indexer].tokensSecureStake().add(_tokens) >= minimumIndexerStake, "!minimumIndexerStake" ); // Transfer tokens to stake from caller to this contract TokenUtils.pullTokens(graphToken(), msg.sender, _tokens); // Stake the transferred tokens _stake(_indexer, _tokens); } /** * @dev Unstake tokens from the indexer stake, lock them until thawing period expires. * @param _tokens Amount of tokens to unstake */ function unstake(uint256 _tokens) external override notPartialPaused { address indexer = msg.sender; Stakes.Indexer storage indexerStake = stakes[indexer]; require(_tokens > 0, "!tokens"); require(indexerStake.tokensStaked > 0, "!stake"); require(indexerStake.tokensAvailable() >= _tokens, "!stake-avail"); // Ensure minimum stake uint256 newStake = indexerStake.tokensSecureStake().sub(_tokens); require(newStake == 0 || newStake >= minimumIndexerStake, "!minimumIndexerStake"); // Before locking more tokens, withdraw any unlocked ones uint256 tokensToWithdraw = indexerStake.tokensWithdrawable(); if (tokensToWithdraw > 0) { _withdraw(indexer); } indexerStake.lockTokens(_tokens, thawingPeriod); emit StakeLocked(indexer, indexerStake.tokensLocked, indexerStake.tokensLockedUntil); } /** * @dev Withdraw indexer tokens once the thawing period has passed. */ function withdraw() external override notPaused { _withdraw(msg.sender); } /** * @dev Set the destination where to send rewards. * @param _destination Rewards destination address. If set to zero, rewards will be restaked */ function setRewardsDestination(address _destination) external override { rewardsDestination[msg.sender] = _destination; emit SetRewardsDestination(msg.sender, _destination); } /** * @dev Slash the indexer stake. Delegated tokens are not subject to slashing. * Can only be called by the slasher role. * @param _indexer Address of indexer to slash * @param _tokens Amount of tokens to slash from the indexer stake * @param _reward Amount of reward tokens to send to a beneficiary * @param _beneficiary Address of a beneficiary to receive a reward for the slashing */ function slash( address _indexer, uint256 _tokens, uint256 _reward, address _beneficiary ) external override onlySlasher notPartialPaused { Stakes.Indexer storage indexerStake = stakes[_indexer]; // Only able to slash a non-zero number of tokens require(_tokens > 0, "!tokens"); // Rewards comes from tokens slashed balance require(_tokens >= _reward, "rewards>slash"); // Cannot slash stake of an indexer without any or enough stake require(indexerStake.tokensStaked > 0, "!stake"); require(_tokens <= indexerStake.tokensStaked, "slash>stake"); // Validate beneficiary of slashed tokens require(_beneficiary != address(0), "!beneficiary"); // Slashing more tokens than freely available (over allocation condition) // Unlock locked tokens to avoid the indexer to withdraw them if (_tokens > indexerStake.tokensAvailable() && indexerStake.tokensLocked > 0) { uint256 tokensOverAllocated = _tokens.sub(indexerStake.tokensAvailable()); uint256 tokensToUnlock = MathUtils.min(tokensOverAllocated, indexerStake.tokensLocked); indexerStake.unlockTokens(tokensToUnlock); } // Remove tokens to slash from the stake indexerStake.release(_tokens); // -- Interactions -- IGraphToken graphToken = graphToken(); // Set apart the reward for the beneficiary and burn remaining slashed stake TokenUtils.burnTokens(graphToken, _tokens.sub(_reward)); // Give the beneficiary a reward for slashing TokenUtils.pushTokens(graphToken, _beneficiary, _reward); emit StakeSlashed(_indexer, _tokens, _reward, _beneficiary); } /** * @dev Delegate tokens to an indexer. * @param _indexer Address of the indexer to delegate tokens to * @param _tokens Amount of tokens to delegate * @return Amount of shares issued of the delegation pool */ function delegate(address _indexer, uint256 _tokens) external override notPartialPaused returns (uint256) { address delegator = msg.sender; // Transfer tokens to delegate to this contract TokenUtils.pullTokens(graphToken(), delegator, _tokens); // Update state return _delegate(delegator, _indexer, _tokens); } /** * @dev Undelegate tokens from an indexer. * @param _indexer Address of the indexer where tokens had been delegated * @param _shares Amount of shares to return and undelegate tokens * @return Amount of tokens returned for the shares of the delegation pool */ function undelegate(address _indexer, uint256 _shares) external override notPartialPaused returns (uint256) { return _undelegate(msg.sender, _indexer, _shares); } /** * @dev Withdraw delegated tokens once the unbonding period has passed. * @param _indexer Withdraw available tokens delegated to indexer * @param _delegateToIndexer Re-delegate to indexer address if non-zero, withdraw if zero address */ function withdrawDelegated(address _indexer, address _delegateToIndexer) external override notPaused returns (uint256) { return _withdrawDelegated(msg.sender, _indexer, _delegateToIndexer); } /** * @dev Allocate available tokens to a subgraph deployment. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _allocationID The allocation identifier * @param _metadata IPFS hash for additional information about the allocation * @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)` */ function allocate( bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external override notPaused { _allocate(msg.sender, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof); } /** * @dev Allocate available tokens to a subgraph deployment. * @param _indexer Indexer address to allocate funds from. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _allocationID The allocation identifier * @param _metadata IPFS hash for additional information about the allocation * @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)` */ function allocateFrom( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external override notPaused { _allocate(_indexer, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof); } /** * @dev Close an allocation and free the staked tokens. * To be eligible for rewards a proof of indexing must be presented. * Presenting a bad proof is subject to slashable condition. * To opt out for rewards set _poi to 0x0 * @param _allocationID The allocation identifier * @param _poi Proof of indexing submitted for the allocated period */ function closeAllocation(address _allocationID, bytes32 _poi) external override notPaused { _closeAllocation(_allocationID, _poi); } /** * @dev Close multiple allocations and free the staked tokens. * To be eligible for rewards a proof of indexing must be presented. * Presenting a bad proof is subject to slashable condition. * To opt out for rewards set _poi to 0x0 * @param _requests An array of CloseAllocationRequest */ function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external override notPaused { for (uint256 i = 0; i < _requests.length; i++) { _closeAllocation(_requests[i].allocationID, _requests[i].poi); } } /** * @dev Close and allocate. This will perform a close and then create a new Allocation * atomically on the same transaction. * @param _closingAllocationID The identifier of the allocation to be closed * @param _poi Proof of indexing submitted for the allocated period * @param _indexer Indexer address to allocate funds from. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _allocationID The allocation identifier * @param _metadata IPFS hash for additional information about the allocation * @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)` */ function closeAndAllocate( address _closingAllocationID, bytes32 _poi, address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external override notPaused { _closeAllocation(_closingAllocationID, _poi); _allocate(_indexer, _subgraphDeploymentID, _tokens, _allocationID, _metadata, _proof); } /** * @dev Collect query fees from state channels and assign them to an allocation. * Funds received are only accepted from a valid sender. * To avoid reverting on the withdrawal from channel flow this function will: * 1) Accept calls with zero tokens. * 2) Accept calls after an allocation passed the dispute period, in that case, all * the received tokens are burned. * @param _tokens Amount of tokens to collect * @param _allocationID Allocation where the tokens will be assigned */ function collect(uint256 _tokens, address _allocationID) external override { // Allocation identifier validation require(_allocationID != address(0), "!alloc"); // The contract caller must be an authorized asset holder require(assetHolders[msg.sender] == true, "!assetHolder"); // Allocation must exist AllocationState allocState = _getAllocationState(_allocationID); require(allocState != AllocationState.Null, "!collect"); // Get allocation Allocation storage alloc = allocations[_allocationID]; uint256 queryFees = _tokens; uint256 curationFees = 0; bytes32 subgraphDeploymentID = alloc.subgraphDeploymentID; // Process query fees only if non-zero amount if (queryFees > 0) { // Pull tokens to collect from the authorized sender IGraphToken graphToken = graphToken(); TokenUtils.pullTokens(graphToken, msg.sender, _tokens); // -- Collect protocol tax -- // If the Allocation is not active or closed we are going to charge a 100% protocol tax uint256 usedProtocolPercentage = (allocState == AllocationState.Active || allocState == AllocationState.Closed) ? protocolPercentage : MAX_PPM; uint256 protocolTax = _collectTax(graphToken, queryFees, usedProtocolPercentage); queryFees = queryFees.sub(protocolTax); // -- Collect curation fees -- // Only if the subgraph deployment is curated curationFees = _collectCurationFees( graphToken, subgraphDeploymentID, queryFees, curationPercentage ); queryFees = queryFees.sub(curationFees); // Add funds to the allocation alloc.collectedFees = alloc.collectedFees.add(queryFees); // When allocation is closed redirect funds to the rebate pool // This way we can keep collecting tokens even after the allocation is closed and // before it gets to the finalized state. if (allocState == AllocationState.Closed) { Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch]; rebatePool.fees = rebatePool.fees.add(queryFees); } } emit AllocationCollected( alloc.indexer, subgraphDeploymentID, epochManager().currentEpoch(), _tokens, _allocationID, msg.sender, curationFees, queryFees ); } /** * @dev Claim tokens from the rebate pool. * @param _allocationID Allocation from where we are claiming tokens * @param _restake True if restake fees instead of transfer to indexer */ function claim(address _allocationID, bool _restake) external override notPaused { _claim(_allocationID, _restake); } /** * @dev Claim tokens from the rebate pool for many allocations. * @param _allocationID Array of allocations from where we are claiming tokens * @param _restake True if restake fees instead of transfer to indexer */ function claimMany(address[] calldata _allocationID, bool _restake) external override notPaused { for (uint256 i = 0; i < _allocationID.length; i++) { _claim(_allocationID[i], _restake); } } /** * @dev Stake tokens on the indexer. * This function does not check minimum indexer stake requirement to allow * to be called by functions that increase the stake when collecting rewards * without reverting * @param _indexer Address of staking party * @param _tokens Amount of tokens to stake */ function _stake(address _indexer, uint256 _tokens) private { // Deposit tokens into the indexer stake stakes[_indexer].deposit(_tokens); // Initialize the delegation pool the first time if (delegationPools[_indexer].updatedAtBlock == 0) { _setDelegationParameters(_indexer, MAX_PPM, MAX_PPM, delegationParametersCooldown); } emit StakeDeposited(_indexer, _tokens); } /** * @dev Withdraw indexer tokens once the thawing period has passed. * @param _indexer Address of indexer to withdraw funds from */ function _withdraw(address _indexer) private { // Get tokens available for withdraw and update balance uint256 tokensToWithdraw = stakes[_indexer].withdrawTokens(); require(tokensToWithdraw > 0, "!tokens"); // Return tokens to the indexer TokenUtils.pushTokens(graphToken(), _indexer, tokensToWithdraw); emit StakeWithdrawn(_indexer, tokensToWithdraw); } /** * @dev Allocate available tokens to a subgraph deployment. * @param _indexer Indexer address to allocate funds from. * @param _subgraphDeploymentID ID of the SubgraphDeployment where tokens will be allocated * @param _tokens Amount of tokens to allocate * @param _allocationID The allocationID will work to identify collected funds related to this allocation * @param _metadata Metadata related to the allocation * @param _proof A 65-bytes Ethereum signed message of `keccak256(indexerAddress,allocationID)` */ function _allocate( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) private { require(_isAuth(_indexer), "!auth"); // Only allocations with a non-zero token amount are allowed require(_tokens > 0, "!tokens"); // Check allocation require(_allocationID != address(0), "!alloc"); require(_getAllocationState(_allocationID) == AllocationState.Null, "!null"); // Caller must prove that they own the private key for the allocationID adddress // The proof is an Ethereum signed message of KECCAK256(indexerAddress,allocationID) bytes32 messageHash = keccak256(abi.encodePacked(_indexer, _allocationID)); bytes32 digest = ECDSA.toEthSignedMessageHash(messageHash); require(ECDSA.recover(digest, _proof) == _allocationID, "!proof"); // Needs to have free capacity not used for other purposes to allocate require(getIndexerCapacity(_indexer) >= _tokens, "!capacity"); // Creates an allocation // Allocation identifiers are not reused // The assetHolder address can send collected funds to the allocation Allocation memory alloc = Allocation( _indexer, _subgraphDeploymentID, _tokens, // Tokens allocated epochManager().currentEpoch(), // createdAtEpoch 0, // closedAtEpoch 0, // Initialize collected fees 0, // Initialize effective allocation _updateRewards(_subgraphDeploymentID) // Initialize accumulated rewards per stake allocated ); allocations[_allocationID] = alloc; // Mark allocated tokens as used stakes[_indexer].allocate(alloc.tokens); // Track total allocations per subgraph // Used for rewards calculations subgraphAllocations[alloc.subgraphDeploymentID] = subgraphAllocations[ alloc.subgraphDeploymentID ] .add(alloc.tokens); emit AllocationCreated( _indexer, _subgraphDeploymentID, alloc.createdAtEpoch, alloc.tokens, _allocationID, _metadata ); } /** * @dev Close an allocation and free the staked tokens. * @param _allocationID The allocation identifier * @param _poi Proof of indexing submitted for the allocated period */ function _closeAllocation(address _allocationID, bytes32 _poi) private { // Allocation must exist and be active AllocationState allocState = _getAllocationState(_allocationID); require(allocState == AllocationState.Active, "!active"); // Get allocation Allocation memory alloc = allocations[_allocationID]; // Validate that an allocation cannot be closed before one epoch alloc.closedAtEpoch = epochManager().currentEpoch(); uint256 epochs = MathUtils.diffOrZero(alloc.closedAtEpoch, alloc.createdAtEpoch); require(epochs > 0, "<epochs"); // Indexer or operator can close an allocation // Delegators are also allowed but only after maxAllocationEpochs passed bool isIndexer = _isAuth(alloc.indexer); if (epochs > maxAllocationEpochs) { require(isIndexer || isDelegator(alloc.indexer, msg.sender), "!auth-or-del"); } else { require(isIndexer, "!auth"); } // Calculate effective allocation for the amount of epochs it remained allocated alloc.effectiveAllocation = _getEffectiveAllocation( maxAllocationEpochs, alloc.tokens, epochs ); // Close the allocation and start counting a period to settle remaining payments from // state channels. allocations[_allocationID].closedAtEpoch = alloc.closedAtEpoch; allocations[_allocationID].effectiveAllocation = alloc.effectiveAllocation; // Account collected fees and effective allocation in rebate pool for the epoch Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch]; if (!rebatePool.exists()) { rebatePool.init(alphaNumerator, alphaDenominator); } rebatePool.addToPool(alloc.collectedFees, alloc.effectiveAllocation); // Distribute rewards if proof of indexing was presented by the indexer or operator if (isIndexer && _poi != 0) { _distributeRewards(_allocationID, alloc.indexer); } else { _updateRewards(alloc.subgraphDeploymentID); } // Free allocated tokens from use stakes[alloc.indexer].unallocate(alloc.tokens); // Track total allocations per subgraph // Used for rewards calculations subgraphAllocations[alloc.subgraphDeploymentID] = subgraphAllocations[ alloc.subgraphDeploymentID ] .sub(alloc.tokens); emit AllocationClosed( alloc.indexer, alloc.subgraphDeploymentID, alloc.closedAtEpoch, alloc.tokens, _allocationID, alloc.effectiveAllocation, msg.sender, _poi, !isIndexer ); } /** * @dev Claim tokens from the rebate pool. * @param _allocationID Allocation from where we are claiming tokens * @param _restake True if restake fees instead of transfer to indexer */ function _claim(address _allocationID, bool _restake) private { // Funds can only be claimed after a period of time passed since allocation was closed AllocationState allocState = _getAllocationState(_allocationID); require(allocState == AllocationState.Finalized, "!finalized"); // Get allocation Allocation memory alloc = allocations[_allocationID]; // Only the indexer or operator can decide if to restake bool restake = _isAuth(alloc.indexer) ? _restake : false; // Process rebate reward Rebates.Pool storage rebatePool = rebates[alloc.closedAtEpoch]; uint256 tokensToClaim = rebatePool.redeem(alloc.collectedFees, alloc.effectiveAllocation); // Add delegation rewards to the delegation pool uint256 delegationRewards = _collectDelegationQueryRewards(alloc.indexer, tokensToClaim); tokensToClaim = tokensToClaim.sub(delegationRewards); // Purge allocation data except for: // - indexer: used in disputes and to avoid reusing an allocationID // - subgraphDeploymentID: used in disputes allocations[_allocationID].tokens = 0; // This avoid collect(), close() and claim() to be called allocations[_allocationID].createdAtEpoch = 0; allocations[_allocationID].closedAtEpoch = 0; allocations[_allocationID].collectedFees = 0; allocations[_allocationID].effectiveAllocation = 0; allocations[_allocationID].accRewardsPerAllocatedToken = 0; // -- Interactions -- IGraphToken graphToken = graphToken(); // When all allocations processed then burn unclaimed fees and prune rebate pool if (rebatePool.unclaimedAllocationsCount == 0) { TokenUtils.burnTokens(graphToken, rebatePool.unclaimedFees()); delete rebates[alloc.closedAtEpoch]; } // When there are tokens to claim from the rebate pool, transfer or restake _sendRewards(graphToken, tokensToClaim, alloc.indexer, restake); emit RebateClaimed( alloc.indexer, alloc.subgraphDeploymentID, _allocationID, epochManager().currentEpoch(), alloc.closedAtEpoch, tokensToClaim, rebatePool.unclaimedAllocationsCount, delegationRewards ); } /** * @dev Delegate tokens to an indexer. * @param _delegator Address of the delegator * @param _indexer Address of the indexer to delegate tokens to * @param _tokens Amount of tokens to delegate * @return Amount of shares issued of the delegation pool */ function _delegate( address _delegator, address _indexer, uint256 _tokens ) private returns (uint256) { // Only delegate a non-zero amount of tokens require(_tokens > 0, "!tokens"); // Only delegate to non-empty address require(_indexer != address(0), "!indexer"); // Only delegate to staked indexer require(stakes[_indexer].tokensStaked > 0, "!stake"); // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; // Collect delegation tax uint256 delegationTax = _collectTax(graphToken(), _tokens, delegationTaxPercentage); uint256 delegatedTokens = _tokens.sub(delegationTax); // Calculate shares to issue uint256 shares = (pool.tokens == 0) ? delegatedTokens : delegatedTokens.mul(pool.shares).div(pool.tokens); // Update the delegation pool pool.tokens = pool.tokens.add(delegatedTokens); pool.shares = pool.shares.add(shares); // Update the delegation delegation.shares = delegation.shares.add(shares); emit StakeDelegated(_indexer, _delegator, delegatedTokens, shares); return shares; } /** * @dev Undelegate tokens from an indexer. * @param _delegator Address of the delegator * @param _indexer Address of the indexer where tokens had been delegated * @param _shares Amount of shares to return and undelegate tokens * @return Amount of tokens returned for the shares of the delegation pool */ function _undelegate( address _delegator, address _indexer, uint256 _shares ) private returns (uint256) { // Can only undelegate a non-zero amount of shares require(_shares > 0, "!shares"); // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; // Delegator need to have enough shares in the pool to undelegate require(delegation.shares >= _shares, "!shares-avail"); // Withdraw tokens if available if (getWithdraweableDelegatedTokens(delegation) > 0) { _withdrawDelegated(_delegator, _indexer, address(0)); } // Calculate tokens to get in exchange for the shares uint256 tokens = _shares.mul(pool.tokens).div(pool.shares); // Update the delegation pool pool.tokens = pool.tokens.sub(tokens); pool.shares = pool.shares.sub(_shares); // Update the delegation delegation.shares = delegation.shares.sub(_shares); delegation.tokensLocked = delegation.tokensLocked.add(tokens); delegation.tokensLockedUntil = epochManager().currentEpoch().add(delegationUnbondingPeriod); emit StakeDelegatedLocked( _indexer, _delegator, tokens, _shares, delegation.tokensLockedUntil ); return tokens; } /** * @dev Withdraw delegated tokens once the unbonding period has passed. * @param _delegator Delegator that is withdrawing tokens * @param _indexer Withdraw available tokens delegated to indexer * @param _delegateToIndexer Re-delegate to indexer address if non-zero, withdraw if zero address */ function _withdrawDelegated( address _delegator, address _indexer, address _delegateToIndexer ) private returns (uint256) { // Get the delegation pool of the indexer DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; // Validation uint256 tokensToWithdraw = getWithdraweableDelegatedTokens(delegation); require(tokensToWithdraw > 0, "!tokens"); // Reset lock delegation.tokensLocked = 0; delegation.tokensLockedUntil = 0; emit StakeDelegatedWithdrawn(_indexer, _delegator, tokensToWithdraw); // -- Interactions -- if (_delegateToIndexer != address(0)) { // Re-delegate tokens to a new indexer _delegate(_delegator, _delegateToIndexer, tokensToWithdraw); } else { // Return tokens to the delegator TokenUtils.pushTokens(graphToken(), _delegator, tokensToWithdraw); } return tokensToWithdraw; } /** * @dev Collect the delegation rewards for query fees. * This function will assign the collected fees to the delegation pool. * @param _indexer Indexer to which the tokens to distribute are related * @param _tokens Total tokens received used to calculate the amount of fees to collect * @return Amount of delegation rewards */ function _collectDelegationQueryRewards(address _indexer, uint256 _tokens) private returns (uint256) { uint256 delegationRewards = 0; DelegationPool storage pool = delegationPools[_indexer]; if (pool.tokens > 0 && pool.queryFeeCut < MAX_PPM) { uint256 indexerCut = uint256(pool.queryFeeCut).mul(_tokens).div(MAX_PPM); delegationRewards = _tokens.sub(indexerCut); pool.tokens = pool.tokens.add(delegationRewards); } return delegationRewards; } /** * @dev Collect the delegation rewards for indexing. * This function will assign the collected fees to the delegation pool. * @param _indexer Indexer to which the tokens to distribute are related * @param _tokens Total tokens received used to calculate the amount of fees to collect * @return Amount of delegation rewards */ function _collectDelegationIndexingRewards(address _indexer, uint256 _tokens) private returns (uint256) { uint256 delegationRewards = 0; DelegationPool storage pool = delegationPools[_indexer]; if (pool.tokens > 0 && pool.indexingRewardCut < MAX_PPM) { uint256 indexerCut = uint256(pool.indexingRewardCut).mul(_tokens).div(MAX_PPM); delegationRewards = _tokens.sub(indexerCut); pool.tokens = pool.tokens.add(delegationRewards); } return delegationRewards; } /** * @dev Collect the curation fees for a subgraph deployment from an amount of tokens. * This function transfer curation fees to the Curation contract by calling Curation.collect * @param _graphToken Token to collect * @param _subgraphDeploymentID Subgraph deployment to which the curation fees are related * @param _tokens Total tokens received used to calculate the amount of fees to collect * @param _curationPercentage Percentage of tokens to collect as fees * @return Amount of curation fees */ function _collectCurationFees( IGraphToken _graphToken, bytes32 _subgraphDeploymentID, uint256 _tokens, uint256 _curationPercentage ) private returns (uint256) { if (_tokens == 0) { return 0; } ICuration curation = curation(); bool isCurationEnabled = _curationPercentage > 0 && address(curation) != address(0); if (isCurationEnabled && curation.isCurated(_subgraphDeploymentID)) { uint256 curationFees = uint256(_curationPercentage).mul(_tokens).div(MAX_PPM); if (curationFees > 0) { // Transfer and call collect() // This function transfer tokens to a trusted protocol contracts // Then we call collect() to do the transfer bookeeping TokenUtils.pushTokens(_graphToken, address(curation), curationFees); curation.collect(_subgraphDeploymentID, curationFees); } return curationFees; } return 0; } /** * @dev Collect tax to burn for an amount of tokens. * @param _graphToken Token to burn * @param _tokens Total tokens received used to calculate the amount of tax to collect * @param _percentage Percentage of tokens to burn as tax * @return Amount of tax charged */ function _collectTax( IGraphToken _graphToken, uint256 _tokens, uint256 _percentage ) private returns (uint256) { uint256 tax = uint256(_percentage).mul(_tokens).div(MAX_PPM); TokenUtils.burnTokens(_graphToken, tax); // Burn tax if any return tax; } /** * @dev Return the current state of an allocation * @param _allocationID Allocation identifier * @return AllocationState */ function _getAllocationState(address _allocationID) private view returns (AllocationState) { Allocation storage alloc = allocations[_allocationID]; if (alloc.indexer == address(0)) { return AllocationState.Null; } if (alloc.tokens == 0) { return AllocationState.Claimed; } uint256 closedAtEpoch = alloc.closedAtEpoch; if (closedAtEpoch == 0) { return AllocationState.Active; } uint256 epochs = epochManager().epochsSince(closedAtEpoch); if (epochs >= channelDisputeEpochs) { return AllocationState.Finalized; } return AllocationState.Closed; } /** * @dev Get the effective stake allocation considering epochs from allocation to closing. * @param _maxAllocationEpochs Max amount of epochs to cap the allocated stake * @param _tokens Amount of tokens allocated * @param _numEpochs Number of epochs that passed from allocation to closing * @return Effective allocated tokens across epochs */ function _getEffectiveAllocation( uint256 _maxAllocationEpochs, uint256 _tokens, uint256 _numEpochs ) private pure returns (uint256) { bool shouldCap = _maxAllocationEpochs > 0 && _numEpochs > _maxAllocationEpochs; return _tokens.mul((shouldCap) ? _maxAllocationEpochs : _numEpochs); } /** * @dev Triggers an update of rewards due to a change in allocations. * @param _subgraphDeploymentID Subgraph deployment updated */ function _updateRewards(bytes32 _subgraphDeploymentID) private returns (uint256) { IRewardsManager rewardsManager = rewardsManager(); if (address(rewardsManager) == address(0)) { return 0; } return rewardsManager.onSubgraphAllocationUpdate(_subgraphDeploymentID); } /** * @dev Assign rewards for the closed allocation to indexer and delegators. * @param _allocationID Allocation */ function _distributeRewards(address _allocationID, address _indexer) private { IRewardsManager rewardsManager = rewardsManager(); if (address(rewardsManager) == address(0)) { return; } // Automatically triggers update of rewards snapshot as allocation will change // after this call. Take rewards mint tokens for the Staking contract to distribute // between indexer and delegators uint256 totalRewards = rewardsManager.takeRewards(_allocationID); if (totalRewards == 0) { return; } // Calculate delegation rewards and add them to the delegation pool uint256 delegationRewards = _collectDelegationIndexingRewards(_indexer, totalRewards); uint256 indexerRewards = totalRewards.sub(delegationRewards); // Send the indexer rewards _sendRewards( graphToken(), indexerRewards, _indexer, rewardsDestination[_indexer] == address(0) ); } /** * @dev Send rewards to the appropiate destination. * @param _graphToken Graph token * @param _amount Number of rewards tokens * @param _beneficiary Address of the beneficiary of rewards * @param _restake Whether to restake or not */ function _sendRewards( IGraphToken _graphToken, uint256 _amount, address _beneficiary, bool _restake ) private { if (_amount == 0) return; if (_restake) { // Restake to place fees into the indexer stake _stake(_beneficiary, _amount); } else { // Transfer funds to the beneficiary's designated rewards destination if set address destination = rewardsDestination[_beneficiary]; TokenUtils.pushTokens( _graphToken, destination == address(0) ? _beneficiary : destination, _amount ); } } } // 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 pragma solidity ^0.7.3; import "./IGraphProxy.sol"; /** * @title Graph Upgradeable * @dev This contract is intended to be inherited from upgradeable contracts. */ contract GraphUpgradeable { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Check if the caller is the proxy admin. */ modifier onlyProxyAdmin(IGraphProxy _proxy) { require(msg.sender == _proxy.admin(), "Caller must be the proxy admin"); _; } /** * @dev Check if the caller is the implementation. */ modifier onlyImpl { require(msg.sender == _implementation(), "Caller must be the implementation"); _; } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Accept to be an implementation of proxy. */ function acceptProxy(IGraphProxy _proxy) external onlyProxyAdmin(_proxy) { _proxy.acceptUpgrade(); } /** * @dev Accept to be an implementation of 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. */ function acceptProxyAndCall(IGraphProxy _proxy, bytes calldata _data) external onlyProxyAdmin(_proxy) { _proxy.acceptUpgradeAndCall(_data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "../token/IGraphToken.sol"; library TokenUtils { /** * @dev Pull tokens from an address to this contract. * @param _graphToken Token to transfer * @param _from Address sending the tokens * @param _amount Amount of tokens to transfer */ function pullTokens( IGraphToken _graphToken, address _from, uint256 _amount ) internal { if (_amount > 0) { require(_graphToken.transferFrom(_from, address(this), _amount), "!transfer"); } } /** * @dev Push tokens from this contract to a receiving address. * @param _graphToken Token to transfer * @param _to Address receiving the tokens * @param _amount Amount of tokens to transfer */ function pushTokens( IGraphToken _graphToken, address _to, uint256 _amount ) internal { if (_amount > 0) { require(_graphToken.transfer(_to, _amount), "!transfer"); } } /** * @dev Burn tokens held by this contract. * @param _graphToken Token to burn * @param _amount Amount of tokens to burn */ function burnTokens(IGraphToken _graphToken, uint256 _amount) internal { if (_amount > 0) { _graphToken.burn(_amount); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import "./IStakingData.sol"; interface IStaking is IStakingData { // -- Allocation Data -- /** * @dev Possible states an allocation can be * States: * - Null = indexer == address(0) * - Active = not Null && tokens > 0 * - Closed = Active && closedAtEpoch != 0 * - Finalized = Closed && closedAtEpoch + channelDisputeEpochs > now() * - Claimed = not Null && tokens == 0 */ enum AllocationState { Null, Active, Closed, Finalized, Claimed } // -- Configuration -- function setMinimumIndexerStake(uint256 _minimumIndexerStake) external; function setThawingPeriod(uint32 _thawingPeriod) external; function setCurationPercentage(uint32 _percentage) external; function setProtocolPercentage(uint32 _percentage) external; function setChannelDisputeEpochs(uint32 _channelDisputeEpochs) external; function setMaxAllocationEpochs(uint32 _maxAllocationEpochs) external; function setRebateRatio(uint32 _alphaNumerator, uint32 _alphaDenominator) external; function setDelegationRatio(uint32 _delegationRatio) external; function setDelegationParameters( uint32 _indexingRewardCut, uint32 _queryFeeCut, uint32 _cooldownBlocks ) external; function setDelegationParametersCooldown(uint32 _blocks) external; function setDelegationUnbondingPeriod(uint32 _delegationUnbondingPeriod) external; function setDelegationTaxPercentage(uint32 _percentage) external; function setSlasher(address _slasher, bool _allowed) external; function setAssetHolder(address _assetHolder, bool _allowed) external; // -- Operation -- function setOperator(address _operator, bool _allowed) external; function isOperator(address _operator, address _indexer) external view returns (bool); // -- Staking -- function stake(uint256 _tokens) external; function stakeTo(address _indexer, uint256 _tokens) external; function unstake(uint256 _tokens) external; function slash( address _indexer, uint256 _tokens, uint256 _reward, address _beneficiary ) external; function withdraw() external; function setRewardsDestination(address _destination) external; // -- Delegation -- function delegate(address _indexer, uint256 _tokens) external returns (uint256); function undelegate(address _indexer, uint256 _shares) external returns (uint256); function withdrawDelegated(address _indexer, address _newIndexer) external returns (uint256); // -- Channel management and allocations -- function allocate( bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function allocateFrom( address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function closeAllocation(address _allocationID, bytes32 _poi) external; function closeAllocationMany(CloseAllocationRequest[] calldata _requests) external; function closeAndAllocate( address _oldAllocationID, bytes32 _poi, address _indexer, bytes32 _subgraphDeploymentID, uint256 _tokens, address _allocationID, bytes32 _metadata, bytes calldata _proof ) external; function collect(uint256 _tokens, address _allocationID) external; function claim(address _allocationID, bool _restake) external; function claimMany(address[] calldata _allocationID, bool _restake) external; // -- Getters and calculations -- function hasStake(address _indexer) external view returns (bool); function getIndexerStakedTokens(address _indexer) external view returns (uint256); function getIndexerCapacity(address _indexer) external view returns (uint256); function getAllocation(address _allocationID) external view returns (Allocation memory); function getAllocationState(address _allocationID) external view returns (AllocationState); function isAllocation(address _allocationID) external view returns (bool); function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID) external view returns (uint256); function getDelegation(address _indexer, address _delegator) external view returns (Delegation memory); function isDelegator(address _indexer, address _delegator) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "../governance/Managed.sol"; import "./IStakingData.sol"; import "./libs/Rebates.sol"; import "./libs/Stakes.sol"; contract StakingV1Storage is Managed { // -- Staking -- // Minimum amount of tokens an indexer needs to stake uint256 public minimumIndexerStake; // Time in blocks to unstake uint32 public thawingPeriod; // in blocks // Percentage of fees going to curators // Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%) uint32 public curationPercentage; // Percentage of fees burned as protocol fee // Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%) uint32 public protocolPercentage; // Period for allocation to be finalized uint32 public channelDisputeEpochs; // Maximum allocation time uint32 public maxAllocationEpochs; // Rebate ratio uint32 public alphaNumerator; uint32 public alphaDenominator; // Indexer stakes : indexer => Stake mapping(address => Stakes.Indexer) public stakes; // Allocations : allocationID => Allocation mapping(address => IStakingData.Allocation) public allocations; // Subgraph Allocations: subgraphDeploymentID => tokens mapping(bytes32 => uint256) public subgraphAllocations; // Rebate pools : epoch => Pool mapping(uint256 => Rebates.Pool) public rebates; // -- Slashing -- // List of addresses allowed to slash stakes mapping(address => bool) public slashers; // -- Delegation -- // Set the delegation capacity multiplier defined by the delegation ratio // If delegation ratio is 100, and an Indexer has staked 5 GRT, // then they can use up to 500 GRT from the delegated stake uint32 public delegationRatio; // Time in blocks an indexer needs to wait to change delegation parameters uint32 public delegationParametersCooldown; // Time in epochs a delegator needs to wait to withdraw delegated stake uint32 public delegationUnbondingPeriod; // in epochs // Percentage of tokens to tax a delegation deposit // Parts per million. (Allows for 4 decimal points, 999,999 = 99.9999%) uint32 public delegationTaxPercentage; // Delegation pools : indexer => DelegationPool mapping(address => IStakingData.DelegationPool) public delegationPools; // -- Operators -- // Operator auth : indexer => operator mapping(address => mapping(address => bool)) public operatorAuth; // -- Asset Holders -- // Allowed AssetHolders: assetHolder => is allowed mapping(address => bool) public assetHolders; } contract StakingV2Storage is StakingV1Storage { // Destination of accrued rewards : beneficiary => rewards destination mapping(address => address) public rewardsDestination; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils Library * @notice A collection of functions to perform math operations */ library MathUtils { using SafeMath for uint256; /** * @dev Calculates the weighted average of two values pondering each of these * values based on configured weights. The contribution of each value N is * weightN/(weightA + weightB). * @param valueA The amount for value A * @param weightA The weight to use for value A * @param valueB The amount for value B * @param weightB The weight to use for value B */ function weightedAverage( uint256 valueA, uint256 weightA, uint256 valueB, uint256 weightB ) internal pure returns (uint256) { return valueA.mul(weightA).add(valueB.mul(weightB)).div(weightA.add(weightB)); } /** * @dev Returns the minimum of two numbers. */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x <= y ? x : y; } /** * @dev Returns the difference between two numbers or zero if negative. */ function diffOrZero(uint256 x, uint256 y) internal pure returns (uint256) { return (x > y) ? x.sub(y) : 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./Cobbs.sol"; /** * @title A collection of data structures and functions to manage Rebates * Used for low-level state changes, require() conditions should be evaluated * at the caller function scope. */ library Rebates { using SafeMath for uint256; // Tracks stats for allocations closed on a particular epoch for claiming // The pool also keeps tracks of total query fees collected and stake used // Only one rebate pool exists per epoch struct Pool { uint256 fees; // total query fees in the rebate pool uint256 effectiveAllocatedStake; // total effective allocation of stake uint256 claimedRewards; // total claimed rewards from the rebate pool uint32 unclaimedAllocationsCount; // amount of unclaimed allocations uint32 alphaNumerator; // numerator of `alpha` in the cobb-douglas function uint32 alphaDenominator; // denominator of `alpha` in the cobb-douglas function } /** * @dev Init the rebate pool with the rebate ratio. * @param _alphaNumerator Numerator of `alpha` in the cobb-douglas function * @param _alphaDenominator Denominator of `alpha` in the cobb-douglas function */ function init( Rebates.Pool storage pool, uint32 _alphaNumerator, uint32 _alphaDenominator ) internal { pool.alphaNumerator = _alphaNumerator; pool.alphaDenominator = _alphaDenominator; } /** * @dev Return true if the rebate pool was already initialized. */ function exists(Rebates.Pool storage pool) internal view returns (bool) { return pool.effectiveAllocatedStake > 0; } /** * @dev Return the amount of unclaimed fees. */ function unclaimedFees(Rebates.Pool storage pool) internal view returns (uint256) { return pool.fees.sub(pool.claimedRewards); } /** * @dev Deposit tokens into the rebate pool. * @param _indexerFees Amount of fees collected in tokens * @param _indexerEffectiveAllocatedStake Effective stake allocated by indexer for a period of epochs */ function addToPool( Rebates.Pool storage pool, uint256 _indexerFees, uint256 _indexerEffectiveAllocatedStake ) internal { pool.fees = pool.fees.add(_indexerFees); pool.effectiveAllocatedStake = pool.effectiveAllocatedStake.add( _indexerEffectiveAllocatedStake ); pool.unclaimedAllocationsCount += 1; } /** * @dev Redeem tokens from the rebate pool. * @param _indexerFees Amount of fees collected in tokens * @param _indexerEffectiveAllocatedStake Effective stake allocated by indexer for a period of epochs * @return Amount of reward tokens according to Cobb-Douglas rebate formula */ function redeem( Rebates.Pool storage pool, uint256 _indexerFees, uint256 _indexerEffectiveAllocatedStake ) internal returns (uint256) { uint256 rebateReward = 0; // Calculate the rebate rewards for the indexer if (pool.fees > 0) { rebateReward = LibCobbDouglas.cobbDouglas( pool.fees, // totalRewards _indexerFees, pool.fees, _indexerEffectiveAllocatedStake, pool.effectiveAllocatedStake, pool.alphaNumerator, pool.alphaDenominator ); // Under NO circumstance we will reward more than total fees in the pool uint256 _unclaimedFees = pool.fees.sub(pool.claimedRewards); if (rebateReward > _unclaimedFees) { rebateReward = _unclaimedFees; } } // Update pool state pool.unclaimedAllocationsCount -= 1; pool.claimedRewards = pool.claimedRewards.add(rebateReward); return rebateReward; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./MathUtils.sol"; /** * @title A collection of data structures and functions to manage the Indexer Stake state. * Used for low-level state changes, require() conditions should be evaluated * at the caller function scope. */ library Stakes { using SafeMath for uint256; using Stakes for Stakes.Indexer; struct Indexer { uint256 tokensStaked; // Tokens on the indexer stake (staked by the indexer) uint256 tokensAllocated; // Tokens used in allocations uint256 tokensLocked; // Tokens locked for withdrawal subject to thawing period uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn } /** * @dev Deposit tokens to the indexer stake. * @param stake Stake data * @param _tokens Amount of tokens to deposit */ function deposit(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensStaked = stake.tokensStaked.add(_tokens); } /** * @dev Release tokens from the indexer stake. * @param stake Stake data * @param _tokens Amount of tokens to release */ function release(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensStaked = stake.tokensStaked.sub(_tokens); } /** * @dev Allocate tokens from the main stack to a SubgraphDeployment. * @param stake Stake data * @param _tokens Amount of tokens to allocate */ function allocate(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensAllocated = stake.tokensAllocated.add(_tokens); } /** * @dev Unallocate tokens from a SubgraphDeployment back to the main stack. * @param stake Stake data * @param _tokens Amount of tokens to unallocate */ function unallocate(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensAllocated = stake.tokensAllocated.sub(_tokens); } /** * @dev Lock tokens until a thawing period pass. * @param stake Stake data * @param _tokens Amount of tokens to unstake * @param _period Period in blocks that need to pass before withdrawal */ function lockTokens( Stakes.Indexer storage stake, uint256 _tokens, uint256 _period ) internal { // Take into account period averaging for multiple unstake requests uint256 lockingPeriod = _period; if (stake.tokensLocked > 0) { lockingPeriod = MathUtils.weightedAverage( MathUtils.diffOrZero(stake.tokensLockedUntil, block.number), // Remaining thawing period stake.tokensLocked, // Weighted by remaining unstaked tokens _period, // Thawing period _tokens // Weighted by new tokens to unstake ); } // Update balances stake.tokensLocked = stake.tokensLocked.add(_tokens); stake.tokensLockedUntil = block.number.add(lockingPeriod); } /** * @dev Unlock tokens. * @param stake Stake data * @param _tokens Amount of tokens to unkock */ function unlockTokens(Stakes.Indexer storage stake, uint256 _tokens) internal { stake.tokensLocked = stake.tokensLocked.sub(_tokens); if (stake.tokensLocked == 0) { stake.tokensLockedUntil = 0; } } /** * @dev Take all tokens out from the locked stake for withdrawal. * @param stake Stake data * @return Amount of tokens being withdrawn */ function withdrawTokens(Stakes.Indexer storage stake) internal returns (uint256) { // Calculate tokens that can be released uint256 tokensToWithdraw = stake.tokensWithdrawable(); if (tokensToWithdraw > 0) { // Reset locked tokens stake.unlockTokens(tokensToWithdraw); // Decrease indexer stake stake.release(tokensToWithdraw); } return tokensToWithdraw; } /** * @dev Return the amount of tokens used in allocations and locked for withdrawal. * @param stake Stake data * @return Token amount */ function tokensUsed(Stakes.Indexer memory stake) internal pure returns (uint256) { return stake.tokensAllocated.add(stake.tokensLocked); } /** * @dev Return the amount of tokens staked not considering the ones that are already going * through the thawing period or are ready for withdrawal. We call it secure stake because * it is not subject to change by a withdraw call from the indexer. * @param stake Stake data * @return Token amount */ function tokensSecureStake(Stakes.Indexer memory stake) internal pure returns (uint256) { return stake.tokensStaked.sub(stake.tokensLocked); } /** * @dev Tokens free balance on the indexer stake that can be used for any purpose. * Any token that is allocated cannot be used as well as tokens that are going through the * thawing period or are withdrawable * Calc: tokensStaked - tokensAllocated - tokensLocked * @param stake Stake data * @return Token amount */ function tokensAvailable(Stakes.Indexer memory stake) internal pure returns (uint256) { return stake.tokensAvailableWithDelegation(0); } /** * @dev Tokens free balance on the indexer stake that can be used for allocations. * This function accepts a parameter for extra delegated capacity that takes into * account delegated tokens * @param stake Stake data * @param _delegatedCapacity Amount of tokens used from delegators to calculate availability * @return Token amount */ function tokensAvailableWithDelegation(Stakes.Indexer memory stake, uint256 _delegatedCapacity) internal pure returns (uint256) { uint256 tokensCapacity = stake.tokensStaked.add(_delegatedCapacity); uint256 _tokensUsed = stake.tokensUsed(); // If more tokens are used than the current capacity, the indexer is overallocated. // This means the indexer doesn't have available capacity to create new allocations. // We can reach this state when the indexer has funds allocated and then any // of these conditions happen: // - The delegationCapacity ratio is reduced. // - The indexer stake is slashed. // - A delegator removes enough stake. if (_tokensUsed > tokensCapacity) { // Indexer stake is over allocated: return 0 to avoid stake to be used until // the overallocation is restored by staking more tokens, unallocating tokens // or using more delegated funds return 0; } return tokensCapacity.sub(_tokensUsed); } /** * @dev Tokens available for withdrawal after thawing period. * @param stake Stake data * @return Token amount */ function tokensWithdrawable(Stakes.Indexer memory stake) internal view returns (uint256) { // No tokens to withdraw before locking period if (stake.tokensLockedUntil == 0 || block.number < stake.tokensLockedUntil) { return 0; } return stake.tokensLocked; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; interface IGraphProxy { function admin() external returns (address); function setAdmin(address _newAdmin) external; function implementation() external returns (address); function pendingImplementation() external returns (address); function upgradeTo(address _newImplementation) external; function acceptUpgrade() external; function acceptUpgradeAndCall(bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IGraphToken is IERC20 { // -- Mint and Burn -- function burn(uint256 amount) external; function mint(address _to, uint256 _amount) external; // -- Mint Admin -- function addMinter(address _account) external; function removeMinter(address _account) external; function renounceMinter() external; function isMinter(address _account) external view returns (bool); // -- Permit -- function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IStakingData { /** * @dev Allocate GRT tokens for the purpose of serving queries of a subgraph deployment * An allocation is created in the allocate() function and consumed in claim() */ struct Allocation { address indexer; bytes32 subgraphDeploymentID; uint256 tokens; // Tokens allocated to a SubgraphDeployment uint256 createdAtEpoch; // Epoch when it was created uint256 closedAtEpoch; // Epoch when it was closed uint256 collectedFees; // Collected fees for the allocation uint256 effectiveAllocation; // Effective allocation when closed uint256 accRewardsPerAllocatedToken; // Snapshot used for reward calc } /** * @dev Represents a request to close an allocation with a specific proof of indexing. * This is passed when calling closeAllocationMany to define the closing parameters for * each allocation. */ struct CloseAllocationRequest { address allocationID; bytes32 poi; } // -- Delegation Data -- /** * @dev Delegation pool information. One per indexer. */ struct DelegationPool { uint32 cooldownBlocks; // Blocks to wait before updating parameters uint32 indexingRewardCut; // in PPM uint32 queryFeeCut; // in PPM uint256 updatedAtBlock; // Block when the pool was last updated uint256 tokens; // Total tokens as pool reserves uint256 shares; // Total shares minted in the pool mapping(address => Delegation) delegators; // Mapping of delegator => Delegation } /** * @dev Individual delegation data of a delegator in a pool. */ struct Delegation { uint256 shares; // Shares owned by a delegator in the pool uint256 tokensLocked; // Tokens locked for undelegation uint256 tokensLockedUntil; // Block when locked tokens can be withdrawn } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./IController.sol"; import "../curation/ICuration.sol"; import "../epochs/IEpochManager.sol"; import "../rewards/IRewardsManager.sol"; import "../staking/IStaking.sol"; import "../token/IGraphToken.sol"; /** * @title Graph Managed contract * @dev The Managed contract provides an interface to interact with the Controller. * It also provides local caching for contract addresses. This mechanism relies on calling the * public `syncAllContracts()` function whenever a contract changes in the controller. * * Inspired by Livepeer: * https://github.com/livepeer/protocol/blob/streamflow/contracts/Controller.sol */ contract Managed { // -- State -- // Controller that contract is registered with IController public controller; mapping(bytes32 => address) private addressCache; uint256[10] private __gap; // -- Events -- event ParameterUpdated(string param); event SetController(address controller); /** * @dev Emitted when contract with `nameHash` is synced to `contractAddress`. */ event ContractSynced(bytes32 indexed nameHash, address contractAddress); // -- Modifiers -- function _notPartialPaused() internal view { require(!controller.paused(), "Paused"); require(!controller.partialPaused(), "Partial-paused"); } function _notPaused() internal view { require(!controller.paused(), "Paused"); } function _onlyGovernor() internal view { require(msg.sender == controller.getGovernor(), "Caller must be Controller governor"); } function _onlyController() internal view { require(msg.sender == address(controller), "Caller must be Controller"); } modifier notPartialPaused { _notPartialPaused(); _; } modifier notPaused { _notPaused(); _; } // Check if sender is controller. modifier onlyController() { _onlyController(); _; } // Check if sender is the governor. modifier onlyGovernor() { _onlyGovernor(); _; } // -- Functions -- /** * @dev Initialize the controller. */ function _initialize(address _controller) internal { _setController(_controller); } /** * @notice Set Controller. Only callable by current controller. * @param _controller Controller contract address */ function setController(address _controller) external onlyController { _setController(_controller); } /** * @dev Set controller. * @param _controller Controller contract address */ function _setController(address _controller) internal { require(_controller != address(0), "Controller must be set"); controller = IController(_controller); emit SetController(_controller); } /** * @dev Return Curation interface. * @return Curation contract registered with Controller */ function curation() internal view returns (ICuration) { return ICuration(_resolveContract(keccak256("Curation"))); } /** * @dev Return EpochManager interface. * @return Epoch manager contract registered with Controller */ function epochManager() internal view returns (IEpochManager) { return IEpochManager(_resolveContract(keccak256("EpochManager"))); } /** * @dev Return RewardsManager interface. * @return Rewards manager contract registered with Controller */ function rewardsManager() internal view returns (IRewardsManager) { return IRewardsManager(_resolveContract(keccak256("RewardsManager"))); } /** * @dev Return Staking interface. * @return Staking contract registered with Controller */ function staking() internal view returns (IStaking) { return IStaking(_resolveContract(keccak256("Staking"))); } /** * @dev Return GraphToken interface. * @return Graph token contract registered with Controller */ function graphToken() internal view returns (IGraphToken) { return IGraphToken(_resolveContract(keccak256("GraphToken"))); } /** * @dev Resolve a contract address from the cache or the Controller if not found. * @return Address of the contract */ function _resolveContract(bytes32 _nameHash) internal view returns (address) { address contractAddress = addressCache[_nameHash]; if (contractAddress == address(0)) { contractAddress = controller.getContractProxy(_nameHash); } return contractAddress; } /** * @dev Cache a contract address from the Controller registry. * @param _name Name of the contract to sync into the cache */ function _syncContract(string memory _name) internal { bytes32 nameHash = keccak256(abi.encodePacked(_name)); address contractAddress = controller.getContractProxy(nameHash); if (addressCache[nameHash] != contractAddress) { addressCache[nameHash] = contractAddress; emit ContractSynced(nameHash, contractAddress); } } /** * @dev Sync protocol contract addresses from the Controller registry. * This function will cache all the contracts using the latest addresses * Anyone can call the function whenever a Proxy contract change in the * controller to ensure the protocol is using the latest version */ function syncAllContracts() external { _syncContract("Curation"); _syncContract("EpochManager"); _syncContract("RewardsManager"); _syncContract("Staking"); _syncContract("GraphToken"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IController { function getGovernor() external view returns (address); // -- Registry -- function setContractProxy(bytes32 _id, address _contractAddress) external; function unsetContractProxy(bytes32 _id) external; function updateController(bytes32 _id, address _controller) external; function getContractProxy(bytes32 _id) external view returns (address); // -- Pausing -- function setPartialPaused(bool _partialPaused) external; function setPaused(bool _paused) external; function setPauseGuardian(address _newPauseGuardian) external; function paused() external view returns (bool); function partialPaused() external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./IGraphCurationToken.sol"; interface ICuration { // -- Pool -- struct CurationPool { uint256 tokens; // GRT Tokens stored as reserves for the subgraph deployment uint32 reserveRatio; // Ratio for the bonding curve IGraphCurationToken gcs; // Curation token contract for this curation pool } // -- Configuration -- function setDefaultReserveRatio(uint32 _defaultReserveRatio) external; function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external; function setCurationTaxPercentage(uint32 _percentage) external; // -- Curation -- function mint( bytes32 _subgraphDeploymentID, uint256 _tokensIn, uint256 _signalOutMin ) external returns (uint256, uint256); function burn( bytes32 _subgraphDeploymentID, uint256 _signalIn, uint256 _tokensOutMin ) external returns (uint256); function collect(bytes32 _subgraphDeploymentID, uint256 _tokens) external; // -- Getters -- function isCurated(bytes32 _subgraphDeploymentID) external view returns (bool); function getCuratorSignal(address _curator, bytes32 _subgraphDeploymentID) external view returns (uint256); function getCurationPoolSignal(bytes32 _subgraphDeploymentID) external view returns (uint256); function getCurationPoolTokens(bytes32 _subgraphDeploymentID) external view returns (uint256); function tokensToSignal(bytes32 _subgraphDeploymentID, uint256 _tokensIn) external view returns (uint256, uint256); function signalToTokens(bytes32 _subgraphDeploymentID, uint256 _signalIn) external view returns (uint256); function curationTaxPercentage() external view returns (uint32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; interface IEpochManager { // -- Configuration -- function setEpochLength(uint256 _epochLength) external; // -- Epochs function runEpoch() external; // -- Getters -- function isCurrentEpochRun() external view returns (bool); function blockNum() external view returns (uint256); function blockHash(uint256 _block) external view returns (bytes32); function currentEpoch() external view returns (uint256); function currentEpochBlock() external view returns (uint256); function currentEpochBlockSinceStart() external view returns (uint256); function epochsSince(uint256 _epoch) external view returns (uint256); function epochsSinceUpdate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; interface IRewardsManager { /** * @dev Stores accumulated rewards and snapshots related to a particular SubgraphDeployment. */ struct Subgraph { uint256 accRewardsForSubgraph; uint256 accRewardsForSubgraphSnapshot; uint256 accRewardsPerSignalSnapshot; uint256 accRewardsPerAllocatedToken; } // -- Params -- function setIssuanceRate(uint256 _issuanceRate) external; // -- Denylist -- function setSubgraphAvailabilityOracle(address _subgraphAvailabilityOracle) external; function setDenied(bytes32 _subgraphDeploymentID, bool _deny) external; function setDeniedMany(bytes32[] calldata _subgraphDeploymentID, bool[] calldata _deny) external; function isDenied(bytes32 _subgraphDeploymentID) external view returns (bool); // -- Getters -- function getNewRewardsPerSignal() external view returns (uint256); function getAccRewardsPerSignal() external view returns (uint256); function getAccRewardsForSubgraph(bytes32 _subgraphDeploymentID) external view returns (uint256); function getAccRewardsPerAllocatedToken(bytes32 _subgraphDeploymentID) external view returns (uint256, uint256); function getRewards(address _allocationID) external view returns (uint256); // -- Updates -- function updateAccRewardsPerSignal() external returns (uint256); function takeRewards(address _allocationID) external returns (uint256); // -- Hooks -- function onSubgraphSignalUpdate(bytes32 _subgraphDeploymentID) external returns (uint256); function onSubgraphAllocationUpdate(bytes32 _subgraphDeploymentID) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IGraphCurationToken is IERC20 { function burnFrom(address _account, uint256 _amount) external; function mint(address _to, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /* Copyright 2019 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. */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "./LibFixedMath.sol"; library LibCobbDouglas { /// @dev The cobb-douglas function used to compute fee-based rewards for /// staking pools in a given epoch. This function does not perform /// bounds checking on the inputs, but the following conditions /// need to be true: /// 0 <= fees / totalFees <= 1 /// 0 <= stake / totalStake <= 1 /// 0 <= alphaNumerator / alphaDenominator <= 1 /// @param totalRewards collected over an epoch. /// @param fees Fees attributed to the the staking pool. /// @param totalFees Total fees collected across all pools that earned rewards. /// @param stake Stake attributed to the staking pool. /// @param totalStake Total stake across all pools that earned rewards. /// @param alphaNumerator Numerator of `alpha` in the cobb-douglas function. /// @param alphaDenominator Denominator of `alpha` in the cobb-douglas /// function. /// @return rewards Rewards owed to the staking pool. function cobbDouglas( uint256 totalRewards, uint256 fees, uint256 totalFees, uint256 stake, uint256 totalStake, uint32 alphaNumerator, uint32 alphaDenominator ) public pure returns (uint256 rewards) { int256 feeRatio = LibFixedMath.toFixed(fees, totalFees); int256 stakeRatio = LibFixedMath.toFixed(stake, totalStake); if (feeRatio == 0 || stakeRatio == 0) { return rewards = 0; } // The cobb-doublas function has the form: // `totalRewards * feeRatio ^ alpha * stakeRatio ^ (1-alpha)` // This is equivalent to: // `totalRewards * stakeRatio * e^(alpha * (ln(feeRatio / stakeRatio)))` // However, because `ln(x)` has the domain of `0 < x < 1` // and `exp(x)` has the domain of `x < 0`, // and fixed-point math easily overflows with multiplication, // we will choose the following if `stakeRatio > feeRatio`: // `totalRewards * stakeRatio / e^(alpha * (ln(stakeRatio / feeRatio)))` // Compute // `e^(alpha * ln(feeRatio/stakeRatio))` if feeRatio <= stakeRatio // or // `e^(alpa * ln(stakeRatio/feeRatio))` if feeRatio > stakeRatio int256 n = feeRatio <= stakeRatio ? LibFixedMath.div(feeRatio, stakeRatio) : LibFixedMath.div(stakeRatio, feeRatio); n = LibFixedMath.exp( LibFixedMath.mulDiv( LibFixedMath.ln(n), int256(alphaNumerator), int256(alphaDenominator) ) ); // Compute // `totalRewards * n` if feeRatio <= stakeRatio // or // `totalRewards / n` if stakeRatio > feeRatio // depending on the choice we made earlier. n = feeRatio <= stakeRatio ? LibFixedMath.mul(stakeRatio, n) : LibFixedMath.div(stakeRatio, n); // Multiply the above with totalRewards. rewards = LibFixedMath.uintMul(n, totalRewards); } } /* Copyright 2017 Bprotocol Foundation, 2019 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. */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.3; // solhint-disable indent /// @dev Signed, fixed-point, 127-bit precision math library. library LibFixedMath { // 1 int256 private constant FIXED_1 = int256( 0x0000000000000000000000000000000080000000000000000000000000000000 ); // 2**255 int256 private constant MIN_FIXED_VAL = int256( 0x8000000000000000000000000000000000000000000000000000000000000000 ); // 1^2 (in fixed-point) int256 private constant FIXED_1_SQUARED = int256( 0x4000000000000000000000000000000000000000000000000000000000000000 ); // 1 int256 private constant LN_MAX_VAL = FIXED_1; // e ^ -63.875 int256 private constant LN_MIN_VAL = int256( 0x0000000000000000000000000000000000000000000000000000000733048c5a ); // 0 int256 private constant EXP_MAX_VAL = 0; // -63.875 int256 private constant EXP_MIN_VAL = -int256( 0x0000000000000000000000000000001ff0000000000000000000000000000000 ); /// @dev Get one as a fixed-point number. function one() internal pure returns (int256 f) { f = FIXED_1; } /// @dev Returns the addition of two fixed point numbers, reverting on overflow. function add(int256 a, int256 b) internal pure returns (int256 c) { c = _add(a, b); } /// @dev Returns the addition of two fixed point numbers, reverting on overflow. function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b == MIN_FIXED_VAL) { revert("out-of-bounds"); } c = _add(a, -b); } /// @dev Returns the multiplication of two fixed point numbers, reverting on overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = _mul(a, b) / FIXED_1; } /// @dev Returns the division of two fixed point numbers. function div(int256 a, int256 b) internal pure returns (int256 c) { c = _div(_mul(a, FIXED_1), b); } /// @dev Performs (a * n) / d, without scaling for precision. function mulDiv( int256 a, int256 n, int256 d ) internal pure returns (int256 c) { c = _div(_mul(a, n), d); } /// @dev Returns the unsigned integer result of multiplying a fixed-point /// number with an integer, reverting if the multiplication overflows. /// Negative results are clamped to zero. function uintMul(int256 f, uint256 u) internal pure returns (uint256) { if (int256(u) < int256(0)) { revert("out-of-bounds"); } int256 c = _mul(f, int256(u)); if (c <= 0) { return 0; } return uint256(uint256(c) >> 127); } /// @dev Returns the absolute value of a fixed point number. function abs(int256 f) internal pure returns (int256 c) { if (f == MIN_FIXED_VAL) { revert("out-of-bounds"); } if (f >= 0) { c = f; } else { c = -f; } } /// @dev Returns 1 / `x`, where `x` is a fixed-point number. function invert(int256 f) internal pure returns (int256 c) { c = _div(FIXED_1_SQUARED, f); } /// @dev Convert signed `n` / 1 to a fixed-point number. function toFixed(int256 n) internal pure returns (int256 f) { f = _mul(n, FIXED_1); } /// @dev Convert signed `n` / `d` to a fixed-point number. function toFixed(int256 n, int256 d) internal pure returns (int256 f) { f = _div(_mul(n, FIXED_1), d); } /// @dev Convert unsigned `n` / 1 to a fixed-point number. /// Reverts if `n` is too large to fit in a fixed-point number. function toFixed(uint256 n) internal pure returns (int256 f) { if (int256(n) < int256(0)) { revert("out-of-bounds"); } f = _mul(int256(n), FIXED_1); } /// @dev Convert unsigned `n` / `d` to a fixed-point number. /// Reverts if `n` / `d` is too large to fit in a fixed-point number. function toFixed(uint256 n, uint256 d) internal pure returns (int256 f) { if (int256(n) < int256(0)) { revert("out-of-bounds"); } if (int256(d) < int256(0)) { revert("out-of-bounds"); } f = _div(_mul(int256(n), FIXED_1), int256(d)); } /// @dev Convert a fixed-point number to an integer. function toInteger(int256 f) internal pure returns (int256 n) { return f / FIXED_1; } /// @dev Get the natural logarithm of a fixed-point number 0 < `x` <= LN_MAX_VAL function ln(int256 x) internal pure returns (int256 r) { if (x > LN_MAX_VAL) { revert("out-of-bounds"); } if (x <= 0) { revert("too-small"); } if (x == FIXED_1) { return 0; } if (x <= LN_MIN_VAL) { return EXP_MIN_VAL; } int256 y; int256 z; int256 w; // Rewrite the input as a quotient of negative natural exponents and a single residual q, such that 1 < q < 2 // For example: log(0.3) = log(e^-1 * e^-0.25 * 1.0471028872385522) // = 1 - 0.25 - log(1 + 0.0471028872385522) // e ^ -32 if (x <= int256(0x00000000000000000000000000000000000000000001c8464f76164760000000)) { r -= int256(0x0000000000000000000000000000001000000000000000000000000000000000); // - 32 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000000000001c8464f76164760000000); // / e ^ -32 } // e ^ -16 if (x <= int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000)) { r -= int256(0x0000000000000000000000000000000800000000000000000000000000000000); // - 16 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000); // / e ^ -16 } // e ^ -8 if (x <= int256(0x00000000000000000000000000000000000afe10820813d78000000000000000)) { r -= int256(0x0000000000000000000000000000000400000000000000000000000000000000); // - 8 x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000afe10820813d78000000000000000); // / e ^ -8 } // e ^ -4 if (x <= int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000)) { r -= int256(0x0000000000000000000000000000000200000000000000000000000000000000); // - 4 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000); // / e ^ -4 } // e ^ -2 if (x <= int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000)) { r -= int256(0x0000000000000000000000000000000100000000000000000000000000000000); // - 2 x = (x * FIXED_1) / int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000); // / e ^ -2 } // e ^ -1 if (x <= int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000)) { r -= int256(0x0000000000000000000000000000000080000000000000000000000000000000); // - 1 x = (x * FIXED_1) / int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000); // / e ^ -1 } // e ^ -0.5 if (x <= int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000)) { r -= int256(0x0000000000000000000000000000000040000000000000000000000000000000); // - 0.5 x = (x * FIXED_1) / int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000); // / e ^ -0.5 } // e ^ -0.25 if (x <= int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000)) { r -= int256(0x0000000000000000000000000000000020000000000000000000000000000000); // - 0.25 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000); // / e ^ -0.25 } // e ^ -0.125 if (x <= int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) { r -= int256(0x0000000000000000000000000000000010000000000000000000000000000000); // - 0.125 x = (x * FIXED_1) / int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d); // / e ^ -0.125 } // `x` is now our residual in the range of 1 <= x <= 2 (or close enough). // Add the taylor series for log(1 + z), where z = x - 1 z = y = x - FIXED_1; w = (y * y) / FIXED_1; r += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02 r += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04 r += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06 r += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08 r += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10 r += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12 r += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14 r += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 } /// @dev Compute the natural exponent for a fixed-point number EXP_MIN_VAL <= `x` <= 1 function exp(int256 x) internal pure returns (int256 r) { if (x < EXP_MIN_VAL) { // Saturate to zero below EXP_MIN_VAL. return 0; } if (x == 0) { return FIXED_1; } if (x > EXP_MAX_VAL) { revert("out-of-bounds"); } // Rewrite the input as a product of natural exponents and a // single residual q, where q is a number of small magnitude. // For example: e^-34.419 = e^(-32 - 2 - 0.25 - 0.125 - 0.044) // = e^-32 * e^-2 * e^-0.25 * e^-0.125 * e^-0.044 // -> q = -0.044 // Multiply with the taylor series for e^q int256 y; int256 z; // q = x % 0.125 (the residual) z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000; z = (z * y) / FIXED_1; r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; r += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; r += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; r += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; r += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; r += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; r += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; r += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; r += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; r += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; r += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; r += z * 0x0000000000000001; // add y^20 * (20! / 20!) r = r / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! // Multiply with the non-residual terms. x = -x; // e ^ -32 if ((x & int256(0x0000000000000000000000000000001000000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000000000f1aaddd7742e56d32fb9f99744)) / int256(0x0000000000000000000000000043cbaf42a000812488fc5c220ad7b97bf6e99e); // * e ^ -32 } // e ^ -16 if ((x & int256(0x0000000000000000000000000000000800000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000000afe10820813d65dfe6a33c07f738f)) / int256(0x000000000000000000000000000005d27a9f51c31b7c2f8038212a0574779991); // * e ^ -16 } // e ^ -8 if ((x & int256(0x0000000000000000000000000000000400000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000002582ab704279e8efd15e0265855c47a)) / int256(0x0000000000000000000000000000001b4c902e273a58678d6d3bfdb93db96d02); // * e ^ -8 } // e ^ -4 if ((x & int256(0x0000000000000000000000000000000200000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000001152aaa3bf81cb9fdb76eae12d029571)) / int256(0x00000000000000000000000000000003b1cc971a9bb5b9867477440d6d157750); // * e ^ -4 } // e ^ -2 if ((x & int256(0x0000000000000000000000000000000100000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000002f16ac6c59de6f8d5d6f63c1482a7c86)) / int256(0x000000000000000000000000000000015bf0a8b1457695355fb8ac404e7a79e3); // * e ^ -2 } // e ^ -1 if ((x & int256(0x0000000000000000000000000000000080000000000000000000000000000000)) != 0) { r = (r * int256(0x000000000000000000000000000000004da2cbf1be5827f9eb3ad1aa9866ebb3)) / int256(0x00000000000000000000000000000000d3094c70f034de4b96ff7d5b6f99fcd8); // * e ^ -1 } // e ^ -0.5 if ((x & int256(0x0000000000000000000000000000000040000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000063afbe7ab2082ba1a0ae5e4eb1b479dc)) / int256(0x00000000000000000000000000000000a45af1e1f40c333b3de1db4dd55f29a7); // * e ^ -0.5 } // e ^ -0.25 if ((x & int256(0x0000000000000000000000000000000020000000000000000000000000000000)) != 0) { r = (r * int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) / int256(0x00000000000000000000000000000000910b022db7ae67ce76b441c27035c6a1); // * e ^ -0.25 } // e ^ -0.125 if ((x & int256(0x0000000000000000000000000000000010000000000000000000000000000000)) != 0) { r = (r * int256(0x00000000000000000000000000000000783eafef1c0a8f3978c7f81824d62ebf)) / int256(0x0000000000000000000000000000000088415abbe9a76bead8d00cf112e4d4a8); // * e ^ -0.125 } } /// @dev Returns the multiplication two numbers, reverting on overflow. function _mul(int256 a, int256 b) private pure returns (int256 c) { if (a == 0) { return 0; } c = a * b; if (c / a != b || c / b != a) { revert("overflow"); } } /// @dev Returns the division of two numbers, reverting on division by zero. function _div(int256 a, int256 b) private pure returns (int256 c) { if (b == 0) { revert("overflow"); } if (a == MIN_FIXED_VAL && b == -1) { revert("overflow"); } c = a / b; } /// @dev Adds two numbers, reverting on overflow. function _add(int256 a, int256 b) private pure returns (int256 c) { c = a + b; if ((a < 0 && b < 0 && c > a) || (a > 0 && b > 0 && c < a)) { revert("overflow"); } } }
Delegate tokens to an indexer. _delegator Address of the delegator _indexer Address of the indexer to delegate tokens to _tokens Amount of tokens to delegate return Amount of shares issued of the delegation pool/ Only delegate a non-zero amount of tokens Only delegate to non-empty address Only delegate to staked indexer Get the delegation pool of the indexer Collect delegation tax Calculate shares to issue Update the delegation pool Update the delegation
function _delegate( address _delegator, address _indexer, uint256 _tokens ) private returns (uint256) { require(_tokens > 0, "!tokens"); require(_indexer != address(0), "!indexer"); require(stakes[_indexer].tokensStaked > 0, "!stake"); DelegationPool storage pool = delegationPools[_indexer]; Delegation storage delegation = pool.delegators[_delegator]; uint256 delegationTax = _collectTax(graphToken(), _tokens, delegationTaxPercentage); uint256 delegatedTokens = _tokens.sub(delegationTax); uint256 shares = (pool.tokens == 0) ? delegatedTokens : delegatedTokens.mul(pool.shares).div(pool.tokens); pool.tokens = pool.tokens.add(delegatedTokens); pool.shares = pool.shares.add(shares); delegation.shares = delegation.shares.add(shares); emit StakeDelegated(_indexer, _delegator, delegatedTokens, shares); return shares; }
6,055,188
./full_match/44787/0xBDb3FAF8fD6668cc92931191e9388B5335cbfBe1/sources/contracts/OffsetHelper.sol
Allow users to withdraw tokens they have deposited./
function withdraw(address _erc20Addr, uint256 _amount) public { require(balances[msg.sender][_erc20Addr] >= _amount, "Insufficient balance"); IERC20(_erc20Addr).safeTransfer(msg.sender, _amount); balances[msg.sender][_erc20Addr] -= _amount; }
13,286,469
./full_match/5/0xfd16CEC145F5C3BD9a21aB34d505CF564d1cD1d4/sources/src/Narwhal.sol
take AUM snapshot at closing
function adminOpenDeposit(bool open) external whenNotPaused onlyOwner { poolOpen = open; if (open) { poolSettle = false; } else { for (uint256 i = 0; i < supportedTokens.length; ++i) { address token = supportedTokens[i]; for (uint256 j = 0; j < pools.length; ++j) { address pool = pools[j]; poolTokenAum[pool][token] = IERC20(token).balanceOf(pool); } } } emit DepositOpened(open); }
7,089,749
./full_match/1/0x930AAD10a036b44708e9B371D284DA4a547B95AE/sources/browser/ETHERBOOBS.sol
Provable function/
function updatePrice() public payable { if (provable_getPrice("URL") > address(this).balance) { LogNewProvableQuery("Provable query was NOT sent, please add some ETH to cover for the query fee"); LogNewProvableQuery("Provable query was sent, standing by for the answer.."); } }
17,054,621
./full_match/1/0x4fd5Ae48A869c5ec0214CB050D2D713433515D8d/sources/contracts/feeders/QuickswapLPFeeder.sol
get current timmestamp return _getTimestamp();
function getTimestamp() external view override returns (uint256) { return now; }
9,715,984
// 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: contracts/ERC20.sol pragma solidity 0.6.10; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 internal _totalSupply; /** * @dev Total number of tokens in existence. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public virtual returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public virtual returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses. * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } /** * @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/Ownable.sol pragma solidity 0.6.10; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the a * specified account. * @param initalOwner The address of the inital owner. */ constructor(address initalOwner) internal { _owner = initalOwner; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Only owner can call"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Owner should not be 0 address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Bella.sol pragma solidity 0.6.10; /** * @title Bella * @dev Bella is an ownable, mintable, pausable and burnable ERC20 token */ contract Bella is ERC20, Ownable { using SafeMath for uint; string public constant name = "Bella"; uint8 public constant decimals = 18; string public constant symbol = "BEL"; uint public constant initalSupply = 1 * 10**8 * 10**uint(decimals); // 100 million bool public paused; // True when circulation is paused. mapping (address => bool) public freezed; mapping (address => bool) public minter; /** * @dev Throws if called by any account that is not a minter. */ modifier onlyMinter() { require(minter[msg.sender], "Only minter can call"); _; } /** * @dev Throws if called when the circulation is paused. */ modifier whenNotPaused() { require(paused == false, "Cirlulation paused!"); _; } /** * @dev The Bella constructor sets the original manager of the contract to the a * specified account, and send all the inital supply to it. * @param manager The address of the first manager of this contract. */ constructor(address manager) public Ownable(manager) { _balances[manager] = initalSupply; _totalSupply = initalSupply; } /** * @dev Add an address to the minter list. * @param minterAddress The address to be added as a minter. */ function addMinter(address minterAddress) public onlyOwner { minter[minterAddress] = true; } /** * @dev Remove an address from the minter list. * @param minterAddress The address to be removed from minters. */ function removeMinter(address minterAddress) public onlyOwner { minter[minterAddress] = false; } /** * @dev Function to mint tokens by a minter * @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, uint value) public onlyMinter returns (bool) { _mint(to, value); return true; } /** * @dev Function to pause all the circulation in the case of emergency. */ function pause() public onlyOwner { paused = true; } /** * @dev Function to recover all the circulation from emergency. */ function unpause() public onlyOwner { paused = false; } /** * @dev Function to freeze a specific user's circulation from emergency. * @param user The user to freeze */ function freeze(address user) public onlyOwner { freezed[user] = true; } /** * @dev Function to recover a specific user's circulation from emergency. * @param user The user to recover */ function unfreeze(address user) public onlyOwner { freezed[user] = false; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance. * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } function transfer(address to, uint256 value) public whenNotPaused override returns (bool) { require(!freezed[msg.sender] && !freezed[to], "target user is freezed"); return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused override returns (bool) { require(!freezed[from] && !freezed[to], "target user is freezed"); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused override returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused override returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused override returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } }
Function to pause all the circulation in the case of emergency./
function pause() public onlyOwner { paused = true; }
2,289
./full_match/1/0xe05447ae2426c4bEb7733c90058C00cC32ABfe49/sources/src/Kong/Treasury.sol
Withdraw stuck token from treasury _amount Amount of token to remove _token Address of token to remove
function withdrawStuckToken(uint256 _amount, address _token) external onlyOwner { require(_token != uniswapV2Router.WETH(), "Can not withdraw WETH"); require(_token != uniswapV2Pair, "Can not withdraw LP"); IERC20(_token).transfer(msg.sender, _amount); }
8,304,421
./full_match/5/0x23c4aC6762A6BfFED15dee634D3C8Dc42EE2Bd11/sources/contracts/CrowdFunding.sol
mapping of the compaign
function donatedToCampaign(uint256 _id) public payable { uint256 amount = msg.value; Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount); if (sent) { campaign.amountCollected = campaign.amountCollected + amount; } }
1,952,393
pragma solidity 0.4.24; pragma experimental "v0.5.0"; /* Copyright 2018 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // File: openzeppelin-solidity/contracts/math/Math.sol /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a >= _b ? _a : _b; } function min64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a < _b ? _a : _b; } function max256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a >= _b ? _a : _b; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/lib/AccessControlledBase.sol /** * @title AccessControlledBase * @author dYdX * * Base functionality for access control. Requires an implementation to * provide a way to grant and optionally revoke access */ contract AccessControlledBase { // ============ State Variables ============ mapping (address => bool) public authorized; // ============ Events ============ event AccessGranted( address who ); event AccessRevoked( address who ); // ============ Modifiers ============ modifier requiresAuthorization() { require( authorized[msg.sender], "AccessControlledBase#requiresAuthorization: Sender not authorized" ); _; } } // File: contracts/lib/StaticAccessControlled.sol /** * @title StaticAccessControlled * @author dYdX * * Allows for functions to be access controled * Permissions cannot be changed after a grace period */ contract StaticAccessControlled is AccessControlledBase, Ownable { using SafeMath for uint256; // ============ State Variables ============ // Timestamp after which no additional access can be granted uint256 public GRACE_PERIOD_EXPIRATION; // ============ Constructor ============ constructor( uint256 gracePeriod ) public Ownable() { GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod); } // ============ Owner-Only State-Changing Functions ============ function grantAccess( address who ) external onlyOwner { require( block.timestamp < GRACE_PERIOD_EXPIRATION, "StaticAccessControlled#grantAccess: Cannot grant access after grace period" ); emit AccessGranted(who); authorized[who] = true; } } // File: contracts/lib/GeneralERC20.sol /** * @title GeneralERC20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we dont automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface GeneralERC20 { function totalSupply( ) external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); function transfer( address to, uint256 value ) external; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; } // File: contracts/lib/TokenInteract.sol /** * @title TokenInteract * @author dYdX * * This library contains functions for interacting with ERC20 tokens */ library TokenInteract { function balanceOf( address token, address owner ) internal view returns (uint256) { return GeneralERC20(token).balanceOf(owner); } function allowance( address token, address owner, address spender ) internal view returns (uint256) { return GeneralERC20(token).allowance(owner, spender); } function approve( address token, address spender, uint256 amount ) internal { GeneralERC20(token).approve(spender, amount); require( checkSuccess(), "TokenInteract#approve: Approval failed" ); } function transfer( address token, address to, uint256 amount ) internal { address from = address(this); if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transfer(to, amount); require( checkSuccess(), "TokenInteract#transfer: Transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transferFrom(from, to, amount); require( checkSuccess(), "TokenInteract#transferFrom: TransferFrom failed" ); } // ============ Private Helper-Functions ============ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. */ function checkSuccess( ) private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } return returnValue != 0; } } // File: contracts/margin/TokenProxy.sol /** * @title TokenProxy * @author dYdX * * Used to transfer tokens between addresses which have set allowance on this contract. */ contract TokenProxy is StaticAccessControlled { using SafeMath for uint256; // ============ Constructor ============ constructor( uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) {} // ============ Authorized-Only State Changing Functions ============ /** * Transfers tokens from an address (that has set allowance on the proxy) to another address. * * @param token The address of the ERC20 token * @param from The address to transfer token from * @param to The address to transfer tokens to * @param value The number of tokens to transfer */ function transferTokens( address token, address from, address to, uint256 value ) external requiresAuthorization { TokenInteract.transferFrom( token, from, to, value ); } // ============ Public Constant Functions ============ /** * Getter function to get the amount of token that the proxy is able to move for a particular * address. The minimum of 1) the balance of that address and 2) the allowance given to proxy. * * @param who The owner of the tokens * @param token The address of the ERC20 token * @return The number of tokens able to be moved by the proxy from the address specified */ function available( address who, address token ) external view returns (uint256) { return Math.min256( TokenInteract.allowance(token, who, address(this)), TokenInteract.balanceOf(token, who) ); } } // File: contracts/margin/Vault.sol /** * @title Vault * @author dYdX * * Holds and transfers tokens in vaults denominated by id * * Vault only supports ERC20 tokens, and will not accept any tokens that require * a tokenFallback or equivalent function (See ERC223, ERC777, etc.) */ contract Vault is StaticAccessControlled { using SafeMath for uint256; // ============ Events ============ event ExcessTokensWithdrawn( address indexed token, address indexed to, address caller ); // ============ State Variables ============ // Address of the TokenProxy contract. Used for moving tokens. address public TOKEN_PROXY; // Map from vault ID to map from token address to amount of that token attributed to the // particular vault ID. mapping (bytes32 => mapping (address => uint256)) public balances; // Map from token address to total amount of that token attributed to some account. mapping (address => uint256) public totalBalances; // ============ Constructor ============ constructor( address proxy, uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) { TOKEN_PROXY = proxy; } // ============ Owner-Only State-Changing Functions ============ /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY * will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { uint256 actualBalance = TokenInteract.balanceOf(token, address(this)); uint256 accountedBalance = totalBalances[token]; uint256 withdrawableBalance = actualBalance.sub(accountedBalance); require( withdrawableBalance != 0, "Vault#withdrawExcessToken: Withdrawable token amount must be non-zero" ); TokenInteract.transfer(token, to, withdrawableBalance); emit ExcessTokensWithdrawn(token, to, msg.sender); return withdrawableBalance; } // ============ Authorized-Only State-Changing Functions ============ /** * Transfers tokens from an address (that has approved the proxy) to the vault. * * @param id The vault which will receive the tokens * @param token ERC20 token address * @param from Address from which the tokens will be taken * @param amount Number of the token to be sent */ function transferToVault( bytes32 id, address token, address from, uint256 amount ) external requiresAuthorization { // First send tokens to this contract TokenProxy(TOKEN_PROXY).transferTokens( token, from, address(this), amount ); // Then increment balances balances[id][token] = balances[id][token].add(amount); totalBalances[token] = totalBalances[token].add(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); validateBalance(token); } /** * Transfers a certain amount of funds to an address. * * @param id The vault from which to send the tokens * @param token ERC20 token address * @param to Address to transfer tokens to * @param amount Number of the token to be sent */ function transferFromVault( bytes32 id, address token, address to, uint256 amount ) external requiresAuthorization { // Next line also asserts that (balances[id][token] >= amount); balances[id][token] = balances[id][token].sub(amount); // Next line also asserts that (totalBalances[token] >= amount); totalBalances[token] = totalBalances[token].sub(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); // Do the sending TokenInteract.transfer(token, to, amount); // asserts transfer succeeded // Final validation validateBalance(token); } // ============ Private Helper-Functions ============ /** * Verifies that this contract is in control of at least as many tokens as accounted for * * @param token Address of ERC20 token */ function validateBalance( address token ) private view { // The actual balance could be greater than totalBalances[token] because anyone // can send tokens to the contract's address which cannot be accounted for assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]); } } // File: contracts/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author dYdX * * Optimized version of the well-known ReentrancyGuard contract */ contract ReentrancyGuard { uint256 private _guardCounter = 1; modifier nonReentrant() { uint256 localCounter = _guardCounter + 1; _guardCounter = localCounter; _; require( _guardCounter == localCounter, "Reentrancy check failure" ); } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/lib/Fraction.sol /** * @title Fraction * @author dYdX * * This library contains implementations for fraction structs. */ library Fraction { struct Fraction128 { uint128 num; uint128 den; } } // File: contracts/lib/FractionMath.sol /** * @title FractionMath * @author dYdX * * This library contains safe math functions for manipulating fractions. */ library FractionMath { using SafeMath for uint256; using SafeMath for uint128; /** * Returns a Fraction128 that is equal to a + b * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (sum) */ function add( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { uint256 left = a.num.mul(b.den); uint256 right = b.num.mul(a.den); uint256 denominator = a.den.mul(b.den); // if left + right overflows, prevent overflow if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); } return bound(left.add(right), denominator); } /** * Returns a Fraction128 that is equal to a - (1/2)^d * * @param a The Fraction128 * @param d The power of (1/2) * @return The result */ function sub1Over( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.den % d == 0) { return bound( a.num.sub(a.den.div(d)), a.den ); } return bound( a.num.mul(d).sub(a.den), a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a / d * * @param a The first Fraction128 * @param d The divisor * @return The result (quotient) */ function div( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.num % d == 0) { return bound( a.num.div(d), a.den ); } return bound( a.num, a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a * b. * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (product) */ function mul( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { return bound( a.num.mul(b.num), a.den.mul(b.den) ); } /** * Returns a fraction from two uint256's. Fits them into uint128 if necessary. * * @param num The numerator * @param den The denominator * @return The Fraction128 that matches num/den most closely */ /* solium-disable-next-line security/no-assign-params */ function bound( uint256 num, uint256 den ) internal pure returns (Fraction.Fraction128 memory) { uint256 max = num > den ? num : den; uint256 first128Bits = (max >> 128); if (first128Bits != 0) { first128Bits += 1; num /= first128Bits; den /= first128Bits; } assert(den != 0); // coverage-enable-line assert(den < 2**128); assert(num < 2**128); return Fraction.Fraction128({ num: uint128(num), den: uint128(den) }); } /** * Returns an in-memory copy of a Fraction128 * * @param a The Fraction128 to copy * @return A copy of the Fraction128 */ function copy( Fraction.Fraction128 memory a ) internal pure returns (Fraction.Fraction128 memory) { validate(a); return Fraction.Fraction128({ num: a.num, den: a.den }); } // ============ Private Helper-Functions ============ /** * Asserts that a Fraction128 is valid (i.e. the denominator is non-zero) * * @param a The Fraction128 to validate */ function validate( Fraction.Fraction128 memory a ) private pure { assert(a.den != 0); // coverage-enable-line } } // File: contracts/lib/Exponent.sol /** * @title Exponent * @author dYdX * * This library contains an implementation for calculating e^X for arbitrary fraction X */ library Exponent { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ // 2**128 - 1 uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455; // Number of precomputed integers, X, for E^((1/2)^X) uint256 constant public MAX_PRECOMPUTE_PRECISION = 32; // Number of precomputed integers, X, for E^X uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32; // ============ Public Implementation Functions ============ /** * Returns e^X for any fraction X * * @param X The exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function exp( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { require( precomputePrecision <= MAX_PRECOMPUTE_PRECISION, "Exponent#exp: Precompute precision over maximum" ); Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } // get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2) uint256 integerX = uint256(Xcopy.num).div(Xcopy.den); // if X is less than 1, then just calculate X if (integerX == 0) { return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision); } // get e^integerX Fraction.Fraction128 memory expOfInt = getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS); while (integerX >= NUM_PRECOMPUTED_INTEGERS) { expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS)); integerX -= NUM_PRECOMPUTED_INTEGERS; } // multiply e^integerX by e^decimalX Fraction.Fraction128 memory decimalX = Fraction.Fraction128({ num: Xcopy.num % Xcopy.den, den: Xcopy.den }); return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt); } /** * Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then * Maclaurin Series approximation to reduce error. * * @param X Exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function expHybrid( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION); assert(X.num < X.den); // will also throw if precomputePrecision is larger than the array length in getDenominator Fraction.Fraction128 memory Xtemp = X.copy(); if (Xtemp.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); uint256 d = 1; // 2^i for (uint256 i = 1; i <= precomputePrecision; i++) { d *= 2; // if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d) if (d.mul(Xtemp.num) >= Xtemp.den) { Xtemp = Xtemp.sub1Over(uint128(d)); result = result.mul(getPrecomputedEToTheHalfToThe(i)); } } return result.mul(expMaclaurin(Xtemp, maclaurinPrecision)); } /** * Returns e^X for any X, using Maclaurin Series approximation * * e^X = SUM(X^n / n!) for n >= 0 * e^X = 1 + X/1! + X^2/2! + X^3/3! ... * * @param X Exponent * @param precision Accuracy of Maclaurin terms * @return e^X */ function expMaclaurin( Fraction.Fraction128 memory X, uint256 precision ) internal pure returns (Fraction.Fraction128 memory) { Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); Fraction.Fraction128 memory Xtemp = ONE(); for (uint256 i = 1; i <= precision; i++) { Xtemp = Xtemp.mul(Xcopy.div(uint128(i))); result = result.add(Xtemp); } return result; } /** * Returns a fraction roughly equaling E^((1/2)^x) for integer x */ function getPrecomputedEToTheHalfToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= MAX_PRECOMPUTE_PRECISION); uint128 denominator = [ 125182886983370532117250726298150828301, 206391688497133195273760705512282642279, 265012173823417992016237332255925138361, 300298134811882980317033350418940119802, 319665700530617779809390163992561606014, 329812979126047300897653247035862915816, 335006777809430963166468914297166288162, 337634268532609249517744113622081347950, 338955731696479810470146282672867036734, 339618401537809365075354109784799900812, 339950222128463181389559457827561204959, 340116253979683015278260491021941090650, 340199300311581465057079429423749235412, 340240831081268226777032180141478221816, 340261598367316729254995498374473399540, 340271982485676106947851156443492415142, 340277174663693808406010255284800906112, 340279770782412691177936847400746725466, 340281068849199706686796915841848278311, 340281717884450116236033378667952410919, 340282042402539547492367191008339680733, 340282204661700319870089970029119685699, 340282285791309720262481214385569134454, 340282326356121674011576912006427792656, 340282346638529464274601981200276914173, 340282356779733812753265346086924801364, 340282361850336100329388676752133324799, 340282364385637272451648746721404212564, 340282365653287865596328444437856608255, 340282366287113163939555716675618384724, 340282366604025813553891209601455838559, 340282366762482138471739420386372790954, 340282366841710300958333641874363209044 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } /** * Returns a fraction roughly equaling E^(x) for integer x */ function getPrecomputedEToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= NUM_PRECOMPUTED_INTEGERS); uint128 denominator = [ 340282366920938463463374607431768211455, 125182886983370532117250726298150828301, 46052210507670172419625860892627118820, 16941661466271327126146327822211253888, 6232488952727653950957829210887653621, 2292804553036637136093891217529878878, 843475657686456657683449904934172134, 310297353591408453462393329342695980, 114152017036184782947077973323212575, 41994180235864621538772677139808695, 15448795557622704876497742989562086, 5683294276510101335127414470015662, 2090767122455392675095471286328463, 769150240628514374138961856925097, 282954560699298259527814398449860, 104093165666968799599694528310221, 38293735615330848145349245349513, 14087478058534870382224480725096, 5182493555688763339001418388912, 1906532833141383353974257736699, 701374233231058797338605168652, 258021160973090761055471434334, 94920680509187392077350434438, 34919366901332874995585576427, 12846117181722897538509298435, 4725822410035083116489797150, 1738532907279185132707372378, 639570514388029575350057932, 235284843422800231081973821, 86556456714490055457751527, 31842340925906738090071268, 11714142585413118080082437, 4309392228124372433711936 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } // ============ Private Helper-Functions ============ function ONE() private pure returns (Fraction.Fraction128 memory) { return Fraction.Fraction128({ num: 1, den: 1 }); } } // File: contracts/lib/MathHelpers.sol /** * @title MathHelpers * @author dYdX * * This library helps with common math functions in Solidity */ library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } } // File: contracts/margin/impl/InterestImpl.sol /** * @title InterestImpl * @author dYdX * * A library that calculates continuously compounded interest for principal, time period, and * interest rate. */ library InterestImpl { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11; uint256 constant DEFAULT_MACLAURIN_PRECISION = 5; uint256 constant MAXIMUM_EXPONENT = 80; uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613; // ============ Public Implementation Functions ============ /** * Returns total tokens owed after accruing interest. Continuously compounding and accurate to * roughly 10^18 decimal places. Continuously compounding interest follows the formula: * I = P * e^(R*T) * * @param principal Principal of the interest calculation * @param interestRate Annual nominal interest percentage times 10**6. * (example: 5% = 5e6) * @param secondsOfInterest Number of seconds that interest has been accruing * @return Total amount of tokens owed. Greater than tokenAmount. */ function getCompoundedInterest( uint256 principal, uint256 interestRate, uint256 secondsOfInterest ) public pure returns (uint256) { uint256 numerator = interestRate.mul(secondsOfInterest); uint128 denominator = (10**8) * (365 * 1 days); // interestRate and secondsOfInterest should both be uint32 assert(numerator < 2**128); // fraction representing (Rate * Time) Fraction.Fraction128 memory rt = Fraction.Fraction128({ num: uint128(numerator), den: denominator }); // calculate e^(RT) Fraction.Fraction128 memory eToRT; if (numerator.div(denominator) >= MAXIMUM_EXPONENT) { // degenerate case: cap calculation eToRT = Fraction.Fraction128({ num: E_TO_MAXIUMUM_EXPONENT, den: 1 }); } else { // normal case: calculate e^(RT) eToRT = Exponent.exp( rt, DEFAULT_PRECOMPUTE_PRECISION, DEFAULT_MACLAURIN_PRECISION ); } // e^X for positive X should be greater-than or equal to 1 assert(eToRT.num >= eToRT.den); return safeMultiplyUint256ByFraction(principal, eToRT); } // ============ Private Helper-Functions ============ /** * Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator * and denominator of f are less than 2**128. */ function safeMultiplyUint256ByFraction( uint256 n, Fraction.Fraction128 memory f ) private pure returns (uint256) { uint256 term1 = n.div(2 ** 128); // first 128 bits uint256 term2 = n % (2 ** 128); // second 128 bits // uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f if (term1 > 0) { term1 = term1.mul(f.num); uint256 numBits = MathHelpers.getNumBits(term1); // reduce rounding error by shifting all the way to the left before dividing term1 = MathHelpers.divisionRoundedUp( term1 << (uint256(256).sub(numBits)), f.den); // continue shifting or reduce shifting to get the right number if (numBits > 128) { term1 = term1 << (numBits.sub(128)); } else if (numBits < 128) { term1 = term1 >> (uint256(128).sub(numBits)); } } // calculates term2 = term2 * f term2 = MathHelpers.getPartialAmountRoundedUp( f.num, f.den, term2 ); return term1.add(term2); } } // File: contracts/margin/impl/MarginState.sol /** * @title MarginState * @author dYdX * * Contains state for the Margin contract. Also used by libraries that implement Margin functions. */ library MarginState { struct State { // Address of the Vault contract address VAULT; // Address of the TokenProxy contract address TOKEN_PROXY; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been filled. mapping (bytes32 => uint256) loanFills; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been canceled. mapping (bytes32 => uint256) loanCancels; // Mapping from positionId -> Position, which stores all the open margin positions. mapping (bytes32 => MarginCommon.Position) positions; // Mapping from positionId -> bool, which stores whether the position has previously been // open, but is now closed. mapping (bytes32 => bool) closedPositions; // Mapping from positionId -> uint256, which stores the total amount of owedToken that has // ever been repaid to the lender for each position. Does not reset. mapping (bytes32 => uint256) totalOwedTokenRepaidToLender; } } // File: contracts/margin/interfaces/lender/LoanOwner.sol /** * @title LoanOwner * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a loan sell via the * transferLoan function or the atomic-assign to the "owner" field in a loan offering. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receiveLoanOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/PositionOwner.sol /** * @title PositionOwner * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PositionOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a position via the * transferPosition function or the atomic-assign to the "owner" field when opening a position. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receivePositionOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/TransferInternal.sol /** * @title TransferInternal * @author dYdX * * This library contains the implementation for transferring ownership of loans and positions. */ library TransferInternal { // ============ Events ============ /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a postion was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); // ============ Internal Implementation Functions ============ /** * Returns either the address of the new loan owner, or the address to which they wish to * pass ownership of the loan. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the loan * @param newOwner The intended owner of the loan * @return The address that the intended owner wishes to assign the loan to (may be * the same as the intended owner). */ function grantLoanOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit LoanTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantLoanOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantLoanOwnership: New owner did not consent to owning loan" ); return newOwner; } /** * Returns either the address of the new position owner, or the address to which they wish to * pass ownership of the position. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the position * @param newOwner The intended owner of the position * @return The address that the intended owner wishes to assign the position to (may * be the same as the intended owner). */ function grantPositionOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit PositionTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantPositionOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantPositionOwnership: New owner did not consent to owning position" ); return newOwner; } } // File: contracts/lib/TimestampHelper.sol /** * @title TimestampHelper * @author dYdX * * Helper to get block timestamps in other formats */ library TimestampHelper { function getBlockTimestamp32() internal view returns (uint32) { // Should not still be in-use in the year 2106 assert(uint256(uint32(block.timestamp)) == block.timestamp); assert(block.timestamp > 0); return uint32(block.timestamp); } } // File: contracts/margin/impl/MarginCommon.sol /** * @title MarginCommon * @author dYdX * * This library contains common functions for implementations of public facing Margin functions */ library MarginCommon { using SafeMath for uint256; // ============ Structs ============ struct Position { address owedToken; // Immutable address heldToken; // Immutable address lender; address owner; uint256 principal; uint256 requiredDeposit; uint32 callTimeLimit; // Immutable uint32 startTimestamp; // Immutable, cannot be 0 uint32 callTimestamp; uint32 maxDuration; // Immutable uint32 interestRate; // Immutable uint32 interestPeriod; // Immutable } struct LoanOffering { address owedToken; address heldToken; address payer; address owner; address taker; address positionOwner; address feeRecipient; address lenderFeeToken; address takerFeeToken; LoanRates rates; uint256 expirationTimestamp; uint32 callTimeLimit; uint32 maxDuration; uint256 salt; bytes32 loanHash; bytes signature; } struct LoanRates { uint256 maxAmount; uint256 minAmount; uint256 minHeldToken; uint256 lenderFee; uint256 takerFee; uint32 interestRate; uint32 interestPeriod; } // ============ Internal Implementation Functions ============ function storeNewPosition( MarginState.State storage state, bytes32 positionId, Position memory position, address loanPayer ) internal { assert(!positionHasExisted(state, positionId)); assert(position.owedToken != address(0)); assert(position.heldToken != address(0)); assert(position.owedToken != position.heldToken); assert(position.owner != address(0)); assert(position.lender != address(0)); assert(position.maxDuration != 0); assert(position.interestPeriod <= position.maxDuration); assert(position.callTimestamp == 0); assert(position.requiredDeposit == 0); state.positions[positionId].owedToken = position.owedToken; state.positions[positionId].heldToken = position.heldToken; state.positions[positionId].principal = position.principal; state.positions[positionId].callTimeLimit = position.callTimeLimit; state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32(); state.positions[positionId].maxDuration = position.maxDuration; state.positions[positionId].interestRate = position.interestRate; state.positions[positionId].interestPeriod = position.interestPeriod; state.positions[positionId].owner = TransferInternal.grantPositionOwnership( positionId, (position.owner != msg.sender) ? msg.sender : address(0), position.owner ); state.positions[positionId].lender = TransferInternal.grantLoanOwnership( positionId, (position.lender != loanPayer) ? loanPayer : address(0), position.lender ); } function getPositionIdFromNonce( uint256 nonce ) internal view returns (bytes32) { return keccak256(abi.encodePacked(msg.sender, nonce)); } function getUnavailableLoanOfferingAmountImpl( MarginState.State storage state, bytes32 loanHash ) internal view returns (uint256) { return state.loanFills[loanHash].add(state.loanCancels[loanHash]); } function cleanupPosition( MarginState.State storage state, bytes32 positionId ) internal { delete state.positions[positionId]; state.closedPositions[positionId] = true; } function calculateOwedAmount( Position storage position, uint256 closeAmount, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp); return InterestImpl.getCompoundedInterest( closeAmount, position.interestRate, timeElapsed ); } /** * Calculates time elapsed rounded up to the nearest interestPeriod */ function calculateEffectiveTimeElapsed( Position storage position, uint256 timestamp ) internal view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round up to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function calculateLenderAmountForIncreasePosition( Position storage position, uint256 principalToAdd, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp); return InterestImpl.getCompoundedInterest( principalToAdd, position.interestRate, timeElapsed ); } function getLoanOfferingHash( LoanOffering loanOffering ) internal view returns (bytes32) { return keccak256( abi.encodePacked( address(this), loanOffering.owedToken, loanOffering.heldToken, loanOffering.payer, loanOffering.owner, loanOffering.taker, loanOffering.positionOwner, loanOffering.feeRecipient, loanOffering.lenderFeeToken, loanOffering.takerFeeToken, getValuesHash(loanOffering) ) ); } function getPositionBalanceImpl( MarginState.State storage state, bytes32 positionId ) internal view returns(uint256) { return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken); } function containsPositionImpl( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return state.positions[positionId].startTimestamp != 0; } function positionHasExisted( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return containsPositionImpl(state, positionId) || state.closedPositions[positionId]; } function getPositionFromStorage( MarginState.State storage state, bytes32 positionId ) internal view returns (Position storage) { Position storage position = state.positions[positionId]; require( position.startTimestamp != 0, "MarginCommon#getPositionFromStorage: The position does not exist" ); return position; } // ============ Private Helper-Functions ============ /** * Calculates time elapsed rounded down to the nearest interestPeriod */ function calculateEffectiveTimeElapsedForNewLender( Position storage position, uint256 timestamp ) private view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round down to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = elapsed.div(period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function getValuesHash( LoanOffering loanOffering ) private pure returns (bytes32) { return keccak256( abi.encodePacked( loanOffering.rates.maxAmount, loanOffering.rates.minAmount, loanOffering.rates.minHeldToken, loanOffering.rates.lenderFee, loanOffering.rates.takerFee, loanOffering.expirationTimestamp, loanOffering.salt, loanOffering.callTimeLimit, loanOffering.maxDuration, loanOffering.rates.interestRate, loanOffering.rates.interestPeriod ) ); } } // File: contracts/margin/interfaces/PayoutRecipient.sol /** * @title PayoutRecipient * @author dYdX * * Interface that smart contracts must implement in order to be the payoutRecipient in a * closePosition transaction. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PayoutRecipient { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive payout from being the payoutRecipient * in a closePosition transaction. May redistribute any payout as necessary. Throws on error. * * @param positionId Unique ID of the position * @param closeAmount Amount of the position that was closed * @param closer Address of the account or contract that closed the position * @param positionOwner Address of the owner of the position * @param heldToken Address of the ERC20 heldToken * @param payout Number of tokens received from the payout * @param totalHeldToken Total amount of heldToken removed from vault during close * @param payoutInHeldToken True if payout is in heldToken, false if in owedToken * @return True if approved by the receiver */ function receiveClosePositionPayout( bytes32 positionId, uint256 closeAmount, address closer, address positionOwner, address heldToken, uint256 payout, uint256 totalHeldToken, bool payoutInHeldToken ) external /* onlyMargin */ returns (bool); } // File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol /** * @title CloseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CloseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * closeWithoutCounterparty(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at most) the specified amount of the loan was * successfully closed. * * @param closer Address of the caller of closeWithoutCounterparty() * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the loan to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeLoanOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol /** * @title ClosePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a position * owned by the smart contract, allowing more complex logic to control positions. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/impl/ClosePositionShared.sol /** * @title ClosePositionShared * @author dYdX * * This library contains shared functionality between ClosePositionImpl and * CloseWithoutCounterpartyImpl */ library ClosePositionShared { using SafeMath for uint256; // ============ Structs ============ struct CloseTx { bytes32 positionId; uint256 originalPrincipal; uint256 closeAmount; uint256 owedTokenOwed; uint256 startingHeldTokenBalance; uint256 availableHeldToken; address payoutRecipient; address owedToken; address heldToken; address positionOwner; address positionLender; address exchangeWrapper; bool payoutInHeldToken; } // ============ Internal Implementation Functions ============ function closePositionStateUpdate( MarginState.State storage state, CloseTx memory transaction ) internal { // Delete the position, or just decrease the principal if (transaction.closeAmount == transaction.originalPrincipal) { MarginCommon.cleanupPosition(state, transaction.positionId); } else { assert( transaction.originalPrincipal == state.positions[transaction.positionId].principal ); state.positions[transaction.positionId].principal = transaction.originalPrincipal.sub(transaction.closeAmount); } } function sendTokensToPayoutRecipient( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) internal returns (uint256) { uint256 payout; if (transaction.payoutInHeldToken) { // Send remaining heldToken to payoutRecipient payout = transaction.availableHeldToken.sub(buybackCostInHeldToken); Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.payoutRecipient, payout ); } else { assert(transaction.exchangeWrapper != address(0)); payout = receivedOwedToken.sub(transaction.owedTokenOwed); TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.payoutRecipient, payout ); } if (AddressUtils.isContract(transaction.payoutRecipient)) { require( PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout( transaction.positionId, transaction.closeAmount, msg.sender, transaction.positionOwner, transaction.heldToken, payout, transaction.availableHeldToken, transaction.payoutInHeldToken ), "ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent" ); } // The ending heldToken balance of the vault should be the starting heldToken balance // minus the available heldToken amount assert( MarginCommon.getPositionBalanceImpl(state, transaction.positionId) == transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken) ); return payout; } function createCloseTx( MarginState.State storage state, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) internal returns (CloseTx memory) { // Validate require( payoutRecipient != address(0), "ClosePositionShared#createCloseTx: Payout recipient cannot be 0" ); require( requestedAmount > 0, "ClosePositionShared#createCloseTx: Requested close amount cannot be 0" ); MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 closeAmount = getApprovedAmount( position, positionId, requestedAmount, payoutRecipient, isWithoutCounterparty ); return parseCloseTx( state, position, positionId, closeAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, isWithoutCounterparty ); } // ============ Private Helper-Functions ============ function getApprovedAmount( MarginCommon.Position storage position, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, bool requireLenderApproval ) private returns (uint256) { // Ensure enough principal uint256 allowedAmount = Math.min256(requestedAmount, position.principal); // Ensure owner consent allowedAmount = closePositionOnBehalfOfRecurse( position.owner, msg.sender, payoutRecipient, positionId, allowedAmount ); // Ensure lender consent if (requireLenderApproval) { allowedAmount = closeLoanOnBehalfOfRecurse( position.lender, msg.sender, payoutRecipient, positionId, allowedAmount ); } assert(allowedAmount > 0); assert(allowedAmount <= position.principal); assert(allowedAmount <= requestedAmount); return allowedAmount; } function closePositionOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = ClosePositionDelegator(contractAddr).closeOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closePositionRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closePositionOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } function closeLoanOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closeLoanRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closeLoanOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } // ============ Parsing Functions ============ function parseCloseTx( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 closeAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) private view returns (CloseTx memory) { uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); uint256 availableHeldToken = MathHelpers.getPartialAmount( closeAmount, position.principal, startingHeldTokenBalance ); uint256 owedTokenOwed = 0; if (!isWithoutCounterparty) { owedTokenOwed = MarginCommon.calculateOwedAmount( position, closeAmount, block.timestamp ); } return CloseTx({ positionId: positionId, originalPrincipal: position.principal, closeAmount: closeAmount, owedTokenOwed: owedTokenOwed, startingHeldTokenBalance: startingHeldTokenBalance, availableHeldToken: availableHeldToken, payoutRecipient: payoutRecipient, owedToken: position.owedToken, heldToken: position.heldToken, positionOwner: position.owner, positionLender: position.lender, exchangeWrapper: exchangeWrapper, payoutInHeldToken: payoutInHeldToken }); } } // File: contracts/margin/interfaces/ExchangeWrapper.sol /** * @title ExchangeWrapper * @author dYdX * * Contract interface that Exchange Wrapper smart contracts must implement in order to interface * with other smart contracts through a common interface. */ interface ExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the transaction */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes orderData ) external view returns (uint256); } // File: contracts/margin/impl/ClosePositionImpl.sol /** * @title ClosePositionImpl * @author dYdX * * This library contains the implementation for the closePosition function of Margin */ library ClosePositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData ) public returns (uint256, uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, false ); ( uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) = returnOwedTokensToLender( state, transaction, orderData ); uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, buybackCostInHeldToken, receivedOwedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnClose( transaction, buybackCostInHeldToken, payout ); return ( transaction.closeAmount, payout, transaction.owedTokenOwed ); } // ============ Private Helper-Functions ============ function returnOwedTokensToLender( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, bytes memory orderData ) private returns (uint256, uint256) { uint256 buybackCostInHeldToken = 0; uint256 receivedOwedToken = 0; uint256 lenderOwedToken = transaction.owedTokenOwed; // Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly // from msg.sender if (transaction.exchangeWrapper == address(0)) { require( transaction.payoutInHeldToken, "ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken" ); // No DEX Order; send owedTokens directly from the closer to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, msg.sender, transaction.positionLender, lenderOwedToken ); } else { // Buy back owedTokens using DEX Order and send to lender (buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken( state, transaction, orderData ); // If no owedToken needed for payout: give lender all owedToken, even if more than owed if (transaction.payoutInHeldToken) { assert(receivedOwedToken >= lenderOwedToken); lenderOwedToken = receivedOwedToken; } // Transfer owedToken from the exchange wrapper to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.positionLender, lenderOwedToken ); } state.totalOwedTokenRepaidToLender[transaction.positionId] = state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken); return (buybackCostInHeldToken, receivedOwedToken); } function buyBackOwedToken( MarginState.State storage state, ClosePositionShared.CloseTx transaction, bytes memory orderData ) private returns (uint256, uint256) { // Ask the exchange wrapper the cost in heldToken to buy back the close // amount of owedToken uint256 buybackCostInHeldToken; if (transaction.payoutInHeldToken) { buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper) .getExchangeCost( transaction.owedToken, transaction.heldToken, transaction.owedTokenOwed, orderData ); // Require enough available heldToken to pay for the buyback require( buybackCostInHeldToken <= transaction.availableHeldToken, "ClosePositionImpl#buyBackOwedToken: Not enough available heldToken" ); } else { buybackCostInHeldToken = transaction.availableHeldToken; } // Send the requisite heldToken to do the buyback from vault to exchange wrapper Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.exchangeWrapper, buybackCostInHeldToken ); // Trade the heldToken for the owedToken uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.owedToken, transaction.heldToken, buybackCostInHeldToken, orderData ); require( receivedOwedToken >= transaction.owedTokenOwed, "ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken" ); return (buybackCostInHeldToken, receivedOwedToken); } function logEventOnClose( ClosePositionShared.CloseTx transaction, uint256 buybackCostInHeldToken, uint256 payout ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), transaction.owedTokenOwed, payout, buybackCostInHeldToken, transaction.payoutInHeldToken ); } } // File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol /** * @title CloseWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the closeWithoutCounterpartyImpl function of * Margin */ library CloseWithoutCounterpartyImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closeWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) public returns (uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, true ); uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, 0, // No buyback cost 0 // Did not receive any owedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnCloseWithoutCounterparty(transaction); return ( transaction.closeAmount, heldTokenPayout ); } // ============ Private Helper-Functions ============ function logEventOnCloseWithoutCounterparty( ClosePositionShared.CloseTx transaction ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), 0, transaction.availableHeldToken, 0, true ); } } // File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol /** * @title DepositCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses deposit heldTokens * into a position owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface DepositCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call depositCollateral(). * * @param depositor Address of the caller of the depositCollateral() function * @param positionId Unique ID of the position * @param amount Requested deposit amount * @return This address to accept, a different address to ask that contract */ function depositCollateralOnBehalfOf( address depositor, bytes32 positionId, uint256 amount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/DepositCollateralImpl.sol /** * @title DepositCollateralImpl * @author dYdX * * This library contains the implementation for the deposit function of Margin */ library DepositCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); // ============ Public Implementation Functions ============ function depositCollateralImpl( MarginState.State storage state, bytes32 positionId, uint256 depositAmount ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( depositAmount > 0, "DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0" ); // Ensure owner consent depositCollateralOnBehalfOfRecurse( position.owner, msg.sender, positionId, depositAmount ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, depositAmount ); // cancel margin call if applicable bool marginCallCanceled = false; uint256 requiredDeposit = position.requiredDeposit; if (position.callTimestamp > 0 && requiredDeposit > 0) { if (depositAmount >= requiredDeposit) { position.requiredDeposit = 0; position.callTimestamp = 0; marginCallCanceled = true; } else { position.requiredDeposit = position.requiredDeposit.sub(depositAmount); } } emit AdditionalCollateralDeposited( positionId, depositAmount, msg.sender ); if (marginCallCanceled) { emit MarginCallCanceled( positionId, position.lender, msg.sender, depositAmount ); } } // ============ Private Helper-Functions ============ function depositCollateralOnBehalfOfRecurse( address contractAddr, address depositor, bytes32 positionId, uint256 amount ) private { // no need to ask for permission if (depositor == contractAddr) { return; } address newContractAddr = DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf( depositor, positionId, amount ); // if not equal, recurse if (newContractAddr != contractAddr) { depositCollateralOnBehalfOfRecurse( newContractAddr, depositor, positionId, amount ); } } } // File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol /** * @title ForceRecoverCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses * forceRecoverCollateral() a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ForceRecoverCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * NOTE: If not returning zero address (or not reverting), this contract must assume that Margin * will either revert the entire transaction or that the collateral was forcibly recovered. * * @param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address recoverer, bytes32 positionId, address recipient ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/ForceRecoverCollateralImpl.sol /** * @title ForceRecoverCollateralImpl * @author dYdX * * This library contains the implementation for the forceRecoverCollateral function of Margin */ library ForceRecoverCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); // ============ Public Implementation Functions ============ function forceRecoverCollateralImpl( MarginState.State storage state, bytes32 positionId, address recipient ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Can only force recover after either: // 1) The loan was called and the call period has elapsed // 2) The maxDuration of the position has elapsed require( /* solium-disable-next-line */ ( position.callTimestamp > 0 && block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit) ) || ( block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration) ), "ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet" ); // Ensure lender consent forceRecoverCollateralOnBehalfOfRecurse( position.lender, msg.sender, positionId, recipient ); // Send the tokens uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId); Vault(state.VAULT).transferFromVault( positionId, position.heldToken, recipient, heldTokenRecovered ); // Delete the position // NOTE: Since position is a storage pointer, this will also set all fields on // the position variable to 0 MarginCommon.cleanupPosition( state, positionId ); // Log an event emit CollateralForceRecovered( positionId, recipient, heldTokenRecovered ); return heldTokenRecovered; } // ============ Private Helper-Functions ============ function forceRecoverCollateralOnBehalfOfRecurse( address contractAddr, address recoverer, bytes32 positionId, address recipient ) private { // no need to ask for permission if (recoverer == contractAddr) { return; } address newContractAddr = ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf( recoverer, positionId, recipient ); if (newContractAddr != contractAddr) { forceRecoverCollateralOnBehalfOfRecurse( newContractAddr, recoverer, positionId, recipient ); } } } // File: contracts/lib/TypedSignature.sol /** * @title TypedSignature * @author dYdX * * Allows for ecrecovery of signed hashes with three different prepended messages: * 1) "" * 2) "\x19Ethereum Signed Message:\n32" * 3) "\x19Ethereum Signed Message:\n\x20" */ library TypedSignature { // Solidity does not offer guarantees about enum values, so we define them explicitly uint8 private constant SIGTYPE_INVALID = 0; uint8 private constant SIGTYPE_ECRECOVER_DEC = 1; uint8 private constant SIGTYPE_ECRECOVER_HEX = 2; uint8 private constant SIGTYPE_UNSUPPORTED = 3; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; /** * Gives the address of the signer of a hash. Allows for three common prepended strings. * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes signatureWithType ) internal pure returns (address) { require( signatureWithType.length == 66, "SignatureValidator#validateSignature: invalid signature length" ); uint8 sigType = uint8(signatureWithType[0]); require( sigType > uint8(SIGTYPE_INVALID), "SignatureValidator#validateSignature: invalid signature type" ); require( sigType < uint8(SIGTYPE_UNSUPPORTED), "SignatureValidator#validateSignature: unsupported signature type" ); uint8 v = uint8(signatureWithType[1]); bytes32 r; bytes32 s; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 34)) s := mload(add(signatureWithType, 66)) } bytes32 signedHash; if (sigType == SIGTYPE_ECRECOVER_DEC) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SIGTYPE_ECRECOVER_HEX); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } } // File: contracts/margin/interfaces/LoanOfferingVerifier.sol /** * @title LoanOfferingVerifier * @author dYdX * * Interface that smart contracts must implement to be able to make off-chain generated * loan offerings. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOfferingVerifier { /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * If true is returned, and no errors are thrown by the Margin contract, the loan will have * occurred. This means that verifyLoanOffering can also be used to update internal contract * state on a loan. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan positionOwner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param positionId Unique ID of the position * @param signature Arbitrary bytes; may or may not be an ECDSA signature * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/BorrowShared.sol /** * @title BorrowShared * @author dYdX * * This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl. * Both use a Loan Offering and a DEX Order to open or increase a position. */ library BorrowShared { using SafeMath for uint256; // ============ Structs ============ struct Tx { bytes32 positionId; address owner; uint256 principal; uint256 lenderAmount; MarginCommon.LoanOffering loanOffering; address exchangeWrapper; bool depositInHeldToken; uint256 depositAmount; uint256 collateralAmount; uint256 heldTokenFromSell; } // ============ Internal Implementation Functions ============ /** * Validate the transaction before exchanging heldToken for owedToken */ function validateTxPreSell( MarginState.State storage state, Tx memory transaction ) internal { assert(transaction.lenderAmount >= transaction.principal); require( transaction.principal > 0, "BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed" ); // If the taker is 0x0 then any address can take it. Otherwise only the taker can use it. if (transaction.loanOffering.taker != address(0)) { require( msg.sender == transaction.loanOffering.taker, "BorrowShared#validateTxPreSell: Invalid loan offering taker" ); } // If the positionOwner is 0x0 then any address can be set as the position owner. // Otherwise only the specified positionOwner can be set as the position owner. if (transaction.loanOffering.positionOwner != address(0)) { require( transaction.owner == transaction.loanOffering.positionOwner, "BorrowShared#validateTxPreSell: Invalid position owner" ); } // Require the loan offering to be approved by the payer if (AddressUtils.isContract(transaction.loanOffering.payer)) { getConsentFromSmartContractLender(transaction); } else { require( transaction.loanOffering.payer == TypedSignature.recover( transaction.loanOffering.loanHash, transaction.loanOffering.signature ), "BorrowShared#validateTxPreSell: Invalid loan offering signature" ); } // Validate the amount is <= than max and >= min uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl( state, transaction.loanOffering.loanHash ); require( transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount, "BorrowShared#validateTxPreSell: Loan offering does not have enough available" ); require( transaction.lenderAmount >= transaction.loanOffering.rates.minAmount, "BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount" ); require( transaction.loanOffering.owedToken != transaction.loanOffering.heldToken, "BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken" ); require( transaction.owner != address(0), "BorrowShared#validateTxPreSell: Position owner cannot be 0" ); require( transaction.loanOffering.owner != address(0), "BorrowShared#validateTxPreSell: Loan owner cannot be 0" ); require( transaction.loanOffering.expirationTimestamp > block.timestamp, "BorrowShared#validateTxPreSell: Loan offering is expired" ); require( transaction.loanOffering.maxDuration > 0, "BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration" ); require( transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration, "BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration" ); // The minimum heldToken is validated after executing the sell // Position and loan ownership is validated in TransferInternal } /** * Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store * how much of the loan was used. */ function doPostSell( MarginState.State storage state, Tx memory transaction ) internal { validateTxPostSell(transaction); // Transfer feeTokens from trader and lender transferLoanFees(state, transaction); // Update global amounts for the loan state.loanFills[transaction.loanOffering.loanHash] = state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount); } /** * Sells the owedToken from the lender (and from the deposit if in owedToken) using the * exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for * maxHeldTokenToBuy of heldTokens at most. */ function doSell( MarginState.State storage state, Tx transaction, bytes orderData, uint256 maxHeldTokenToBuy ) internal returns (uint256) { // Move owedTokens from lender to exchange wrapper pullOwedTokensFromLender(state, transaction); // Sell just the lender's owedToken (if trader deposit is in heldToken) // Otherwise sell both the lender's owedToken and the trader's deposit in owedToken uint256 sellAmount = transaction.depositInHeldToken ? transaction.lenderAmount : transaction.lenderAmount.add(transaction.depositAmount); // Do the trade, taking only the maxHeldTokenToBuy if more is returned uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData ) ); // Move the tokens to the vault Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, transaction.exchangeWrapper, heldTokenFromSell ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell); return heldTokenFromSell; } /** * Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can * be sold for heldToken. */ function doDepositOwedToken( MarginState.State storage state, Tx transaction ) internal { TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, msg.sender, transaction.exchangeWrapper, transaction.depositAmount ); } /** * Take the heldToken deposit from the trader and move it to the vault. */ function doDepositHeldToken( MarginState.State storage state, Tx transaction ) internal { Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, msg.sender, transaction.depositAmount ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount); } // ============ Private Helper-Functions ============ function validateTxPostSell( Tx transaction ) private pure { uint256 expectedCollateral = transaction.depositInHeldToken ? transaction.heldTokenFromSell.add(transaction.depositAmount) : transaction.heldTokenFromSell; assert(transaction.collateralAmount == expectedCollateral); uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minHeldToken ); require( transaction.collateralAmount >= loanOfferingMinimumHeldToken, "BorrowShared#validateTxPostSell: Loan offering minimum held token not met" ); } function getConsentFromSmartContractLender( Tx transaction ) private { verifyLoanOfferingRecurse( transaction.loanOffering.payer, getLoanOfferingAddresses(transaction), getLoanOfferingValues256(transaction), getLoanOfferingValues32(transaction), transaction.positionId, transaction.loanOffering.signature ); } function verifyLoanOfferingRecurse( address contractAddr, address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) private { address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering( addresses, values256, values32, positionId, signature ); if (newContractAddr != contractAddr) { verifyLoanOfferingRecurse( newContractAddr, addresses, values256, values32, positionId, signature ); } } function pullOwedTokensFromLender( MarginState.State storage state, Tx transaction ) private { // Transfer owedToken to the exchange wrapper TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, transaction.loanOffering.payer, transaction.exchangeWrapper, transaction.lenderAmount ); } function transferLoanFees( MarginState.State storage state, Tx transaction ) private { // 0 fee address indicates no fees if (transaction.loanOffering.feeRecipient == address(0)) { return; } TokenProxy proxy = TokenProxy(state.TOKEN_PROXY); uint256 lenderFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.lenderFee ); uint256 takerFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.takerFee ); if (lenderFee > 0) { proxy.transferTokens( transaction.loanOffering.lenderFeeToken, transaction.loanOffering.payer, transaction.loanOffering.feeRecipient, lenderFee ); } if (takerFee > 0) { proxy.transferTokens( transaction.loanOffering.takerFeeToken, msg.sender, transaction.loanOffering.feeRecipient, takerFee ); } } function getLoanOfferingAddresses( Tx transaction ) private pure returns (address[9]) { return [ transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.payer, transaction.loanOffering.owner, transaction.loanOffering.taker, transaction.loanOffering.positionOwner, transaction.loanOffering.feeRecipient, transaction.loanOffering.lenderFeeToken, transaction.loanOffering.takerFeeToken ]; } function getLoanOfferingValues256( Tx transaction ) private pure returns (uint256[7]) { return [ transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minAmount, transaction.loanOffering.rates.minHeldToken, transaction.loanOffering.rates.lenderFee, transaction.loanOffering.rates.takerFee, transaction.loanOffering.expirationTimestamp, transaction.loanOffering.salt ]; } function getLoanOfferingValues32( Tx transaction ) private pure returns (uint32[4]) { return [ transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.loanOffering.rates.interestRate, transaction.loanOffering.rates.interestPeriod ]; } } // File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol /** * @title IncreaseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreaseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned loan. Margin will call this on the owner of a loan during increasePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan size was successfully increased. * * @param payer Lender adding additional funds to the position * @param positionId Unique ID of the position * @param principalAdded Principal amount to be added to the position * @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or * zero if increaseWithoutCounterparty() is used). * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol /** * @title IncreasePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreasePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned position. Margin will call this on the owner of a position during increasePosition() * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the position size was successfully increased. * * @param trader Address initiating the addition of funds to the position * @param positionId Unique ID of the position * @param principalAdded Amount of principal to be added to the position * @return This address to accept, a different address to ask that contract */ function increasePositionOnBehalfOf( address trader, bytes32 positionId, uint256 principalAdded ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/IncreasePositionImpl.sol /** * @title IncreasePositionImpl * @author dYdX * * This library contains the implementation for the increasePosition function of Margin */ library IncreasePositionImpl { using SafeMath for uint256; // ============ Events ============ /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function increasePositionImpl( MarginState.State storage state, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (uint256) { // Also ensures that the position exists MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); BorrowShared.Tx memory transaction = parseIncreasePositionTx( position, positionId, addresses, values256, values32, depositInHeldToken, signature ); validateIncrease(state, transaction, position); doBorrowAndSell(state, transaction, orderData); updateState( position, transaction.positionId, transaction.principal, transaction.lenderAmount, transaction.loanOffering.payer ); // LOG EVENT recordPositionIncreased(transaction, position); return transaction.lenderAmount; } function increaseWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 principalToAdd ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Disallow adding 0 principal require( principalToAdd > 0, "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal" ); // Disallow additions after maximum duration require( block.timestamp < uint256(position.startTimestamp).add(position.maxDuration), "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration" ); uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal( state, position, positionId, principalToAdd ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, heldTokenAmount ); updateState( position, positionId, principalToAdd, 0, // lent amount msg.sender ); emit PositionIncreased( positionId, msg.sender, msg.sender, position.owner, position.lender, "", address(0), 0, principalToAdd, 0, heldTokenAmount, true ); return heldTokenAmount; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { // Calculate the number of heldTokens to add uint256 collateralToAdd = getCollateralNeededForAddedPrincipal( state, state.positions[transaction.positionId], transaction.positionId, transaction.principal ); // Do pre-exchange validations BorrowShared.validateTxPreSell(state, transaction); // Calculate and deposit owedToken uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; } // Sell owedToken for heldToken using the exchange wrapper transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, maxHeldTokenFromSell ); // Calculate and deposit heldToken if (transaction.depositInHeldToken) { require( transaction.heldTokenFromSell <= collateralToAdd, "IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken" ); transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell); BorrowShared.doDepositHeldToken(state, transaction); } // Make sure the actual added collateral is what is expected assert(transaction.collateralAmount == collateralToAdd); // Do post-exchange validations BorrowShared.doPostSell(state, transaction); } function getOwedTokenDeposit( BorrowShared.Tx transaction, uint256 collateralToAdd, bytes orderData ) private view returns (uint256) { uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost( transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, collateralToAdd, orderData ); require( transaction.lenderAmount <= totalOwedToken, "IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required" ); return totalOwedToken.sub(transaction.lenderAmount); } function validateIncrease( MarginState.State storage state, BorrowShared.Tx transaction, MarginCommon.Position storage position ) private view { assert(MarginCommon.containsPositionImpl(state, transaction.positionId)); require( position.callTimeLimit <= transaction.loanOffering.callTimeLimit, "IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position" ); // require the position to end no later than the loanOffering's maximum acceptable end time uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration); uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration); require( positionEndTimestamp <= offeringEndTimestamp, "IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position" ); require( block.timestamp < positionEndTimestamp, "IncreasePositionImpl#validateIncrease: Position has passed its maximum duration" ); } function getCollateralNeededForAddedPrincipal( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 principalToAdd ) private view returns (uint256) { uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); return MathHelpers.getPartialAmountRoundedUp( principalToAdd, position.principal, heldTokenBalance ); } function updateState( MarginCommon.Position storage position, bytes32 positionId, uint256 principalAdded, uint256 owedTokenLent, address loanPayer ) private { position.principal = position.principal.add(principalAdded); address owner = position.owner; address lender = position.lender; // Ensure owner consent increasePositionOnBehalfOfRecurse( owner, msg.sender, positionId, principalAdded ); // Ensure lender consent increaseLoanOnBehalfOfRecurse( lender, loanPayer, positionId, principalAdded, owedTokenLent ); } function increasePositionOnBehalfOfRecurse( address contractAddr, address trader, bytes32 positionId, uint256 principalAdded ) private { // Assume owner approval if not a smart contract and they increased their own position if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf( trader, positionId, principalAdded ); if (newContractAddr != contractAddr) { increasePositionOnBehalfOfRecurse( newContractAddr, trader, positionId, principalAdded ); } } function increaseLoanOnBehalfOfRecurse( address contractAddr, address payer, bytes32 positionId, uint256 principalAdded, uint256 amountLent ) private { // Assume lender approval if not a smart contract and they increased their own loan if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf( payer, positionId, principalAdded, amountLent ); if (newContractAddr != contractAddr) { increaseLoanOnBehalfOfRecurse( newContractAddr, payer, positionId, principalAdded, amountLent ); } } function recordPositionIncreased( BorrowShared.Tx transaction, MarginCommon.Position storage position ) private { emit PositionIncreased( transaction.positionId, msg.sender, transaction.loanOffering.payer, position.owner, position.lender, transaction.loanOffering.loanHash, transaction.loanOffering.feeRecipient, transaction.lenderAmount, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseIncreasePositionTx( MarginCommon.Position storage position, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { uint256 principal = values256[7]; uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition( position, principal, block.timestamp ); assert(lenderAmount >= principal); BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: positionId, owner: position.owner, principal: principal, lenderAmount: lenderAmount, loanOffering: parseLoanOfferingFromIncreasePositionTx( position, addresses, values256, values32, signature ), exchangeWrapper: addresses[6], depositInHeldToken: depositInHeldToken, depositAmount: 0, // set later collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOfferingFromIncreasePositionTx( MarginCommon.Position storage position, address[7] addresses, uint256[8] values256, uint32[2] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: position.owedToken, heldToken: position.heldToken, payer: addresses[0], owner: position.lender, taker: addresses[1], positionOwner: addresses[2], feeRecipient: addresses[3], lenderFeeToken: addresses[4], takerFeeToken: addresses[5], rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferingRatesFromIncreasePositionTx( MarginCommon.Position storage position, uint256[8] values256 ) private view returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: position.interestRate, interestPeriod: position.interestPeriod }); return rates; } } // File: contracts/margin/impl/MarginStorage.sol /** * @title MarginStorage * @author dYdX * * This contract serves as the storage for the entire state of MarginStorage */ contract MarginStorage { MarginState.State state; } // File: contracts/margin/impl/LoanGetters.sol /** * @title LoanGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any loan * offering stored in the dYdX protocol. */ contract LoanGetters is MarginStorage { // ============ Public Constant Functions ============ /** * Gets the principal amount of a loan offering that is no longer available. * * @param loanHash Unique hash of the loan offering * @return The total unavailable amount of the loan offering, which is equal to the * filled amount plus the canceled amount. */ function getLoanUnavailableAmount( bytes32 loanHash ) external view returns (uint256) { return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash); } /** * Gets the total amount of owed token lent for a loan. * * @param loanHash Unique hash of the loan offering * @return The total filled amount of the loan offering. */ function getLoanFilledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanFills[loanHash]; } /** * Gets the amount of a loan offering that has been canceled. * * @param loanHash Unique hash of the loan offering * @return The total canceled amount of the loan offering. */ function getLoanCanceledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanCancels[loanHash]; } } // File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol /** * @title CancelMarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses cancel a * margin-call for a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CancelMarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the margin-call was successfully canceled. * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/lender/MarginCallDelegator.sol /** * @title MarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses margin-call a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface MarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call marginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan was successfully margin-called. * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/LoanImpl.sol /** * @title LoanImpl * @author dYdX * * This library contains the implementation for the following functions of Margin: * * - marginCall * - cancelMarginCallImpl * - cancelLoanOffering */ library LoanImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); // ============ Public Implementation Functions ============ function marginCallImpl( MarginState.State storage state, bytes32 positionId, uint256 requiredDeposit ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp == 0, "LoanImpl#marginCallImpl: The position has already been margin-called" ); // Ensure lender consent marginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId, requiredDeposit ); position.callTimestamp = TimestampHelper.getBlockTimestamp32(); position.requiredDeposit = requiredDeposit; emit MarginCallInitiated( positionId, position.lender, position.owner, requiredDeposit ); } function cancelMarginCallImpl( MarginState.State storage state, bytes32 positionId ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp > 0, "LoanImpl#cancelMarginCallImpl: Position has not been margin-called" ); // Ensure lender consent cancelMarginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId ); state.positions[positionId].callTimestamp = 0; state.positions[positionId].requiredDeposit = 0; emit MarginCallCanceled( positionId, position.lender, position.owner, 0 ); } function cancelLoanOfferingImpl( MarginState.State storage state, address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) public returns (uint256) { MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32 ); require( msg.sender == loanOffering.payer, "LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel" ); require( loanOffering.expirationTimestamp > block.timestamp, "LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired" ); uint256 remainingAmount = loanOffering.rates.maxAmount.sub( MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash) ); uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount); // If the loan was already fully canceled, then just return 0 amount was canceled if (amountToCancel == 0) { return 0; } state.loanCancels[loanOffering.loanHash] = state.loanCancels[loanOffering.loanHash].add(amountToCancel); emit LoanOfferingCanceled( loanOffering.loanHash, loanOffering.payer, loanOffering.feeRecipient, amountToCancel ); return amountToCancel; } // ============ Private Helper-Functions ============ function marginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId, uint256 requiredDeposit ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = MarginCallDelegator(contractAddr).marginCallOnBehalfOf( msg.sender, positionId, requiredDeposit ); if (newContractAddr != contractAddr) { marginCallOnBehalfOfRecurse( newContractAddr, who, positionId, requiredDeposit ); } } function cancelMarginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf( msg.sender, positionId ); if (newContractAddr != contractAddr) { cancelMarginCallOnBehalfOfRecurse( newContractAddr, who, positionId ); } } // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32 ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[0], heldToken: addresses[1], payer: addresses[2], owner: addresses[3], taker: addresses[4], positionOwner: addresses[5], feeRecipient: addresses[6], lenderFeeToken: addresses[7], takerFeeToken: addresses[8], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: new bytes(0) }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[7] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], interestRate: values32[2], lenderFee: values256[3], takerFee: values256[4], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/MarginAdmin.sol /** * @title MarginAdmin * @author dYdX * * Contains admin functions for the Margin contract * The owner can put Margin into various close-only modes, which will disallow new position creation */ contract MarginAdmin is Ownable { // ============ Enums ============ // All functionality enabled uint8 private constant OPERATION_STATE_OPERATIONAL = 0; // Only closing functions + cancelLoanOffering allowed (marginCall, closePosition, // cancelLoanOffering, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1; // Only closing functions allowed (marginCall, closePosition, closePositionDirectly, // forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2; // Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3; // This operation state (and any higher) is invalid uint8 private constant OPERATION_STATE_INVALID = 4; // ============ Events ============ /** * Event indicating the operation state has changed */ event OperationStateChanged( uint8 from, uint8 to ); // ============ State Variables ============ uint8 public operationState; // ============ Constructor ============ constructor() public Ownable() { operationState = OPERATION_STATE_OPERATIONAL; } // ============ Modifiers ============ modifier onlyWhileOperational() { require( operationState == OPERATION_STATE_OPERATIONAL, "MarginAdmin#onlyWhileOperational: Can only call while operational" ); _; } modifier cancelLoanOfferingStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY, "MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state" ); _; } modifier closePositionStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY || operationState == OPERATION_STATE_CLOSE_ONLY, "MarginAdmin#closePositionStateControl: Invalid operation state" ); _; } modifier closePositionDirectlyStateControl() { _; } // ============ Owner-Only State-Changing Functions ============ function setOperationState( uint8 newState ) external onlyOwner { require( newState < OPERATION_STATE_INVALID, "MarginAdmin#setOperationState: newState is not a valid operation state" ); if (newState != operationState) { emit OperationStateChanged( operationState, newState ); operationState = newState; } } } // File: contracts/margin/impl/MarginEvents.sol /** * @title MarginEvents * @author dYdX * * Contains events for the Margin contract. * * NOTE: Any Margin function libraries that use events will need to both define the event here * and copy the event into the library itself as libraries don't support sharing events */ contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); } // File: contracts/margin/impl/OpenPositionImpl.sol /** * @title OpenPositionImpl * @author dYdX * * This library contains the implementation for the openPosition function of Margin */ library OpenPositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openPositionImpl( MarginState.State storage state, address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (bytes32) { BorrowShared.Tx memory transaction = parseOpenTx( addresses, values256, values32, depositInHeldToken, signature ); require( !MarginCommon.positionHasExisted(state, transaction.positionId), "OpenPositionImpl#openPositionImpl: positionId already exists" ); doBorrowAndSell(state, transaction, orderData); // Before doStoreNewPosition() so that PositionOpened event is before Transferred events recordPositionOpened( transaction ); doStoreNewPosition( state, transaction ); return transaction.positionId; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { BorrowShared.validateTxPreSell(state, transaction); if (transaction.depositInHeldToken) { BorrowShared.doDepositHeldToken(state, transaction); } else { BorrowShared.doDepositOwedToken(state, transaction); } transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, MathHelpers.maxUint256() ); BorrowShared.doPostSell(state, transaction); } function doStoreNewPosition( MarginState.State storage state, BorrowShared.Tx memory transaction ) private { MarginCommon.storeNewPosition( state, transaction.positionId, MarginCommon.Position({ owedToken: transaction.loanOffering.owedToken, heldToken: transaction.loanOffering.heldToken, lender: transaction.loanOffering.owner, owner: transaction.owner, principal: transaction.principal, requiredDeposit: 0, callTimeLimit: transaction.loanOffering.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: transaction.loanOffering.maxDuration, interestRate: transaction.loanOffering.rates.interestRate, interestPeriod: transaction.loanOffering.rates.interestPeriod }), transaction.loanOffering.payer ); } function recordPositionOpened( BorrowShared.Tx transaction ) private { emit PositionOpened( transaction.positionId, msg.sender, transaction.loanOffering.payer, transaction.loanOffering.loanHash, transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.feeRecipient, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.loanOffering.rates.interestRate, transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseOpenTx( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[9]), owner: addresses[0], principal: values256[7], lenderAmount: values256[7], loanOffering: parseLoanOffering( addresses, values256, values32, signature ), exchangeWrapper: addresses[10], depositInHeldToken: depositInHeldToken, depositAmount: values256[8], collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOffering( address[11] addresses, uint256[10] values256, uint32[4] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[1], heldToken: addresses[2], payer: addresses[3], owner: addresses[4], taker: addresses[5], positionOwner: addresses[6], feeRecipient: addresses[7], lenderFeeToken: addresses[8], takerFeeToken: addresses[9], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[10] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: values32[2], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol /** * @title OpenWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the openWithoutCounterparty * function of Margin */ library OpenWithoutCounterpartyImpl { // ============ Structs ============ struct Tx { bytes32 positionId; address positionOwner; address owedToken; address heldToken; address loanOwner; uint256 principal; uint256 deposit; uint32 callTimeLimit; uint32 maxDuration; uint32 interestRate; uint32 interestPeriod; } // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openWithoutCounterpartyImpl( MarginState.State storage state, address[4] addresses, uint256[3] values256, uint32[4] values32 ) public returns (bytes32) { Tx memory openTx = parseTx( addresses, values256, values32 ); validate( state, openTx ); Vault(state.VAULT).transferToVault( openTx.positionId, openTx.heldToken, msg.sender, openTx.deposit ); recordPositionOpened( openTx ); doStoreNewPosition( state, openTx ); return openTx.positionId; } // ============ Private Helper-Functions ============ function doStoreNewPosition( MarginState.State storage state, Tx memory openTx ) private { MarginCommon.storeNewPosition( state, openTx.positionId, MarginCommon.Position({ owedToken: openTx.owedToken, heldToken: openTx.heldToken, lender: openTx.loanOwner, owner: openTx.positionOwner, principal: openTx.principal, requiredDeposit: 0, callTimeLimit: openTx.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: openTx.maxDuration, interestRate: openTx.interestRate, interestPeriod: openTx.interestPeriod }), msg.sender ); } function validate( MarginState.State storage state, Tx memory openTx ) private view { require( !MarginCommon.positionHasExisted(state, openTx.positionId), "openWithoutCounterpartyImpl#validate: positionId already exists" ); require( openTx.principal > 0, "openWithoutCounterpartyImpl#validate: principal cannot be 0" ); require( openTx.owedToken != address(0), "openWithoutCounterpartyImpl#validate: owedToken cannot be 0" ); require( openTx.owedToken != openTx.heldToken, "openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken" ); require( openTx.positionOwner != address(0), "openWithoutCounterpartyImpl#validate: positionOwner cannot be 0" ); require( openTx.loanOwner != address(0), "openWithoutCounterpartyImpl#validate: loanOwner cannot be 0" ); require( openTx.maxDuration > 0, "openWithoutCounterpartyImpl#validate: maxDuration cannot be 0" ); require( openTx.interestPeriod <= openTx.maxDuration, "openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration" ); } function recordPositionOpened( Tx memory openTx ) private { emit PositionOpened( openTx.positionId, msg.sender, msg.sender, bytes32(0), openTx.owedToken, openTx.heldToken, address(0), openTx.principal, 0, openTx.deposit, openTx.interestRate, openTx.callTimeLimit, openTx.maxDuration, true ); } // ============ Parsing Functions ============ function parseTx( address[4] addresses, uint256[3] values256, uint32[4] values32 ) private view returns (Tx memory) { Tx memory openTx = Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[2]), positionOwner: addresses[0], owedToken: addresses[1], heldToken: addresses[2], loanOwner: addresses[3], principal: values256[0], deposit: values256[1], callTimeLimit: values32[0], maxDuration: values32[1], interestRate: values32[2], interestPeriod: values32[3] }); return openTx; } } // File: contracts/margin/impl/PositionGetters.sol /** * @title PositionGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any position * stored in the dYdX protocol. */ contract PositionGetters is MarginStorage { using SafeMath for uint256; // ============ Public Constant Functions ============ /** * Gets if a position is currently open. * * @param positionId Unique ID of the position * @return True if the position is exists and is open */ function containsPosition( bytes32 positionId ) external view returns (bool) { return MarginCommon.containsPositionImpl(state, positionId); } /** * Gets if a position is currently margin-called. * * @param positionId Unique ID of the position * @return True if the position is margin-called */ function isPositionCalled( bytes32 positionId ) external view returns (bool) { return (state.positions[positionId].callTimestamp > 0); } /** * Gets if a position was previously open and is now closed. * * @param positionId Unique ID of the position * @return True if the position is now closed */ function isPositionClosed( bytes32 positionId ) external view returns (bool) { return state.closedPositions[positionId]; } /** * Gets the total amount of owedToken ever repaid to the lender for a position. * * @param positionId Unique ID of the position * @return Total amount of owedToken ever repaid */ function getTotalOwedTokenRepaidToLender( bytes32 positionId ) external view returns (uint256) { return state.totalOwedTokenRepaidToLender[positionId]; } /** * Gets the amount of heldToken currently locked up in Vault for a particular position. * * @param positionId Unique ID of the position * @return The amount of heldToken */ function getPositionBalance( bytes32 positionId ) external view returns (uint256) { return MarginCommon.getPositionBalanceImpl(state, positionId); } /** * Gets the time until the interest fee charged for the position will increase. * Returns 1 if the interest fee increases every second. * Returns 0 if the interest fee will never increase again. * * @param positionId Unique ID of the position * @return The number of seconds until the interest fee will increase */ function getTimeUntilInterestIncrease( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed( position, block.timestamp ); uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp); if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration return 0; } else { // nextStep is the final second at which the calculated interest fee is the same as it // is currently, so add 1 to get the correct value return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed); } } /** * Gets the amount of owedTokens currently needed to close the position completely, including * interest fees. * * @param positionId Unique ID of the position * @return The number of owedTokens */ function getPositionOwedAmount( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); return MarginCommon.calculateOwedAmount( position, position.principal, block.timestamp ); } /** * Gets the amount of owedTokens needed to close a given principal amount of the position at a * given time, including interest fees. * * @param positionId Unique ID of the position * @param principalToClose Amount of principal being closed * @param timestamp Block timestamp in seconds of close * @return The number of owedTokens owed */ function getPositionOwedAmountAtTime( bytes32 positionId, uint256 principalToClose, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getPositionOwedAmountAtTime: Requested time before position started" ); return MarginCommon.calculateOwedAmount( position, principalToClose, timestamp ); } /** * Gets the amount of owedTokens that can be borrowed from a lender to add a given principal * amount to the position at a given time. * * @param positionId Unique ID of the position * @param principalToAdd Amount being added to principal * @param timestamp Block timestamp in seconds of addition * @return The number of owedTokens that will be borrowed */ function getLenderAmountForIncreasePositionAtTime( bytes32 positionId, uint256 principalToAdd, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start" ); return MarginCommon.calculateLenderAmountForIncreasePosition( position, principalToAdd, timestamp ); } // ============ All Properties ============ /** * Get a Position by id. This does not validate the position exists. If the position does not * exist, all 0's will be returned. * * @param positionId Unique ID of the position * @return Addresses corresponding to: * * [0] = owedToken * [1] = heldToken * [2] = lender * [3] = owner * * Values corresponding to: * * [0] = principal * [1] = requiredDeposit * * Values corresponding to: * * [0] = callTimeLimit * [1] = startTimestamp * [2] = callTimestamp * [3] = maxDuration * [4] = interestRate * [5] = interestPeriod */ function getPosition( bytes32 positionId ) external view returns ( address[4], uint256[2], uint32[6] ) { MarginCommon.Position storage position = state.positions[positionId]; return ( [ position.owedToken, position.heldToken, position.lender, position.owner ], [ position.principal, position.requiredDeposit ], [ position.callTimeLimit, position.startTimestamp, position.callTimestamp, position.maxDuration, position.interestRate, position.interestPeriod ] ); } // ============ Individual Properties ============ function getPositionLender( bytes32 positionId ) external view returns (address) { return state.positions[positionId].lender; } function getPositionOwner( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owner; } function getPositionHeldToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].heldToken; } function getPositionOwedToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owedToken; } function getPositionPrincipal( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].principal; } function getPositionInterestRate( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].interestRate; } function getPositionRequiredDeposit( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].requiredDeposit; } function getPositionStartTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].startTimestamp; } function getPositionCallTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimestamp; } function getPositionCallTimeLimit( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimeLimit; } function getPositionMaxDuration( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].maxDuration; } function getPositioninterestPeriod( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].interestPeriod; } } // File: contracts/margin/impl/TransferImpl.sol /** * @title TransferImpl * @author dYdX * * This library contains the implementation for the transferPosition and transferLoan functions of * Margin */ library TransferImpl { // ============ Public Implementation Functions ============ function transferLoanImpl( MarginState.State storage state, bytes32 positionId, address newLender ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferLoanImpl: Position does not exist" ); address originalLender = state.positions[positionId].lender; require( msg.sender == originalLender, "TransferImpl#transferLoanImpl: Only lender can transfer ownership" ); require( newLender != originalLender, "TransferImpl#transferLoanImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of loan. // That is, newLender may pass ownership to a different address. address finalLender = TransferInternal.grantLoanOwnership( positionId, originalLender, newLender); require( finalLender != originalLender, "TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].lender = finalLender; } function transferPositionImpl( MarginState.State storage state, bytes32 positionId, address newOwner ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferPositionImpl: Position does not exist" ); address originalOwner = state.positions[positionId].owner; require( msg.sender == originalOwner, "TransferImpl#transferPositionImpl: Only position owner can transfer ownership" ); require( newOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of position. // That is, newOwner may pass ownership to a different address. address finalOwner = TransferInternal.grantPositionOwnership( positionId, originalOwner, newOwner); require( finalOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].owner = finalOwner; } } // File: contracts/margin/Margin.sol /** * @title Margin * @author dYdX * * This contract is used to facilitate margin trading as per the dYdX protocol */ contract Margin is ReentrancyGuard, MarginStorage, MarginEvents, MarginAdmin, LoanGetters, PositionGetters { using SafeMath for uint256; // ============ Constructor ============ constructor( address vault, address proxy ) public MarginAdmin() { state = MarginState.State({ VAULT: vault, TOKEN_PROXY: proxy }); } // ============ Public State Changing Functions ============ /** * Open a margin position. Called by the margin trader who must provide both a * signed loan offering as well as a DEX Order with which to sell the owedToken. * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan payer * [4] = loan owner * [5] = loan taker * [6] = loan position owner * [7] = loan fee recipient * [8] = loan lender fee token * [9] = loan taker fee token * [10] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = position amount of principal * [8] = deposit amount * [9] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Unique ID for the new position */ function openPosition( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenPositionImpl.openPositionImpl( state, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Open a margin position without a counterparty. The caller will serve as both the * lender and the position owner * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan owner * * @param values256 Values corresponding to: * * [0] = principal * [1] = deposit amount * [2] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = call time limit (in seconds) * [1] = maxDuration (in seconds) * [2] = interest rate (annual nominal percentage times 10**6) * [3] = interest update period (in seconds) * * @return Unique ID for the new position */ function openWithoutCounterparty( address[4] addresses, uint256[3] values256, uint32[4] values32 ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl( state, addresses, values256, values32 ); } /** * Increase the size of a position. Funds will be borrowed from the loan payer and sold as per * the position. The amount of owedToken borrowed from the lender will be >= the amount of * principal added, as it will incorporate interest already earned by the position so far. * * @param positionId Unique ID of the position * @param addresses Addresses corresponding to: * * [0] = loan payer * [1] = loan taker * [2] = loan position owner * [3] = loan fee recipient * [4] = loan lender fee token * [5] = loan taker fee token * [6] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender * will be >= this amount) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be pulled in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Amount of owedTokens pulled from the lender */ function increasePosition( bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increasePositionImpl( state, positionId, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Increase a position directly by putting up heldToken. The caller will serve as both the * lender and the position owner * * @param positionId Unique ID of the position * @param principalToAdd Principal amount to add to the position * @return Amount of heldToken pulled from the msg.sender */ function increaseWithoutCounterparty( bytes32 positionId, uint256 principalToAdd ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increaseWithoutCounterpartyImpl( state, positionId, principalToAdd ); } /** * Close a position. May be called by the owner or with the approval of the owner. May provide * an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient * is sent the resulting payout. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param exchangeWrapper Address of the exchange wrapper * @param payoutInHeldToken True to pay out the payoutRecipient in heldToken, * False to pay out the payoutRecipient in owedToken * @param order Order object to be passed to the exchange wrapper * @return Values corresponding to: * 1) Principal of position closed * 2) Amount of tokens (heldToken if payoutInHeldtoken is true, * owedToken otherwise) received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePosition( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes order ) external closePositionStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, order ); } /** * Helper to close a position by paying owedToken directly rather than using an exchangeWrapper. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePositionDirectly( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionDirectlyStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, new bytes(0) ); } /** * Reduce the size of a position and withdraw a proportional amount of heldToken from the vault. * Must be approved by both the position owner and lender. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * 3) The amount allowed by the lender if closer != lender * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the msg.sender */ function closeWithoutCounterparty( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionStateControl nonReentrant returns (uint256, uint256) { return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl( state, positionId, requestedCloseAmount, payoutRecipient ); } /** * Margin-call a position. Only callable with the approval of the position lender. After the * call, the position owner will have time equal to the callTimeLimit of the position to close * the position. If the owner does not close the position, the lender can recover the collateral * in the position. * * @param positionId Unique ID of the position * @param requiredDeposit Amount of deposit the position owner will have to put up to cancel * the margin-call. Passing in 0 means the margin call cannot be * canceled by depositing */ function marginCall( bytes32 positionId, uint256 requiredDeposit ) external nonReentrant { LoanImpl.marginCallImpl( state, positionId, requiredDeposit ); } /** * Cancel a margin-call. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position */ function cancelMarginCall( bytes32 positionId ) external onlyWhileOperational nonReentrant { LoanImpl.cancelMarginCallImpl(state, positionId); } /** * Used to recover the heldTokens held as collateral. Is callable after the maximum duration of * the loan has expired or the loan has been margin-called for the duration of the callTimeLimit * but remains unclosed. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return Amount of heldToken recovered */ function forceRecoverCollateral( bytes32 positionId, address recipient ) external nonReentrant returns (uint256) { return ForceRecoverCollateralImpl.forceRecoverCollateralImpl( state, positionId, recipient ); } /** * Deposit additional heldToken as collateral for a position. Cancels margin-call if: * 0 < position.requiredDeposit < depositAmount. Only callable by the position owner. * * @param positionId Unique ID of the position * @param depositAmount Additional amount in heldToken to deposit */ function depositCollateral( bytes32 positionId, uint256 depositAmount ) external onlyWhileOperational nonReentrant { DepositCollateralImpl.depositCollateralImpl( state, positionId, depositAmount ); } /** * Cancel an amount of a loan offering. Only callable by the loan offering's payer. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan position owner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param cancelAmount Amount to cancel * @return Amount that was canceled */ function cancelLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) external cancelLoanOfferingStateControl nonReentrant returns (uint256) { return LoanImpl.cancelLoanOfferingImpl( state, addresses, values256, values32, cancelAmount ); } /** * Transfer ownership of a loan to a new address. This new address will be entitled to all * payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it * must implement the LoanOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the loan */ function transferLoan( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferLoanImpl( state, positionId, who); } /** * Transfer ownership of a position to a new address. This new address will be entitled to all * payouts. Only callable by the owner of a position. If "who" is a contract, it must implement * the PositionOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the position */ function transferPosition( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferPositionImpl( state, positionId, who); } // ============ Public Constant Functions ============ /** * Gets the address of the Vault contract that holds and accounts for tokens. * * @return The address of the Vault contract */ function getVaultAddress() external view returns (address) { return state.VAULT; } /** * Gets the address of the TokenProxy contract that accounts must set allowance on in order to * make loans or open/close positions. * * @return The address of the TokenProxy contract */ function getTokenProxyAddress() external view returns (address) { return state.TOKEN_PROXY; } } // File: contracts/margin/interfaces/OnlyMargin.sol /** * @title OnlyMargin * @author dYdX * * Contract to store the address of the main Margin contract and trust only that address to call * certain functions. */ contract OnlyMargin { // ============ Constants ============ // Address of the known and trusted Margin contract on the blockchain address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Modifiers ============ modifier onlyMargin() { require( msg.sender == DYDX_MARGIN, "OnlyMargin#onlyMargin: Only Margin can call" ); _; } } // File: contracts/margin/external/lib/LoanOfferingParser.sol /** * @title LoanOfferingParser * @author dYdX * * Contract for LoanOfferingVerifiers to parse arguments */ contract LoanOfferingParser { // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes signature ) internal pure returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering; fillLoanOfferingAddresses(loanOffering, addresses); fillLoanOfferingValues256(loanOffering, values256); fillLoanOfferingValues32(loanOffering, values32); loanOffering.signature = signature; return loanOffering; } function fillLoanOfferingAddresses( MarginCommon.LoanOffering memory loanOffering, address[9] addresses ) private pure { loanOffering.owedToken = addresses[0]; loanOffering.heldToken = addresses[1]; loanOffering.payer = addresses[2]; loanOffering.owner = addresses[3]; loanOffering.taker = addresses[4]; loanOffering.positionOwner = addresses[5]; loanOffering.feeRecipient = addresses[6]; loanOffering.lenderFeeToken = addresses[7]; loanOffering.takerFeeToken = addresses[8]; } function fillLoanOfferingValues256( MarginCommon.LoanOffering memory loanOffering, uint256[7] values256 ) private pure { loanOffering.rates.maxAmount = values256[0]; loanOffering.rates.minAmount = values256[1]; loanOffering.rates.minHeldToken = values256[2]; loanOffering.rates.lenderFee = values256[3]; loanOffering.rates.takerFee = values256[4]; loanOffering.expirationTimestamp = values256[5]; loanOffering.salt = values256[6]; } function fillLoanOfferingValues32( MarginCommon.LoanOffering memory loanOffering, uint32[4] values32 ) private pure { loanOffering.callTimeLimit = values32[0]; loanOffering.maxDuration = values32[1]; loanOffering.rates.interestRate = values32[2]; loanOffering.rates.interestPeriod = values32[3]; } } // File: contracts/margin/external/lib/MarginHelper.sol /** * @title MarginHelper * @author dYdX * * This library contains helper functions for interacting with Margin */ library MarginHelper { function getPosition( address DYDX_MARGIN, bytes32 positionId ) internal view returns (MarginCommon.Position memory) { ( address[4] memory addresses, uint256[2] memory values256, uint32[6] memory values32 ) = Margin(DYDX_MARGIN).getPosition(positionId); return MarginCommon.Position({ owedToken: addresses[0], heldToken: addresses[1], lender: addresses[2], owner: addresses[3], principal: values256[0], requiredDeposit: values256[1], callTimeLimit: values32[0], startTimestamp: values32[1], callTimestamp: values32[2], maxDuration: values32[3], interestRate: values32[4], interestPeriod: values32[5] }); } } // File: contracts/margin/external/BucketLender/BucketLender.sol /** * @title BucketLender * @author dYdX * * On-chain shared lender that allows anyone to deposit tokens into this contract to be used to * lend tokens for a particular margin position. * * - Each bucket has three variables: * - Available Amount * - The available amount of tokens that the bucket has to lend out * - Outstanding Principal * - The amount of principal that the bucket is responsible for in the margin position * - Weight * - Used to keep track of each account's weighted ownership within a bucket * - Relative weight between buckets is meaningless * - Only accounts' relative weight within a bucket matters * * - Token Deposits: * - Go into a particular bucket, determined by time since the start of the position * - If the position has not started: bucket = 0 * - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME) * - This is always the highest bucket; no higher bucket yet exists * - Increase the bucket's Available Amount * - Increase the bucket's weight and the account's weight in that bucket * * - Token Withdrawals: * - Can be from any bucket with available amount * - Decrease the bucket's Available Amount * - Decrease the bucket's weight and the account's weight in that bucket * * - Increasing the Position (Lending): * - The lowest buckets with Available Amount are used first * - Decreases Available Amount * - Increases Outstanding Principal * * - Decreasing the Position (Being Paid-Back) * - The highest buckets with Outstanding Principal are paid back first * - Decreases Outstanding Principal * - Increases Available Amount * * * - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from * those buckets for a longer period of time. * - Deposits in the same bucket earn the same interest rate. * - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not * making the maximum interest). * - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket with Available Amount */ contract BucketLender is Ownable, OnlyMargin, LoanOwner, IncreaseLoanDelegator, MarginCallDelegator, CancelMarginCallDelegator, ForceRecoverCollateralDelegator, LoanOfferingParser, LoanOfferingVerifier, ReentrancyGuard { using SafeMath for uint256; using TokenInteract for address; // ============ Events ============ event Deposit( address indexed beneficiary, uint256 bucket, uint256 amount, uint256 weight ); event Withdraw( address indexed withdrawer, uint256 bucket, uint256 weight, uint256 owedTokenWithdrawn, uint256 heldTokenWithdrawn ); event PrincipalIncreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event PrincipalDecreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event AvailableIncreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); event AvailableDecreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); // ============ State Variables ============ /** * Available Amount is the amount of tokens that is available to be lent by each bucket. * These tokens are also available to be withdrawn by the accounts that have weight in the * bucket. */ // Available Amount for each bucket mapping(uint256 => uint256) public availableForBucket; // Total Available Amount uint256 public availableTotal; /** * Outstanding Principal is the share of the margin position's principal that each bucket * is responsible for. That is, each bucket with Outstanding Principal is owed * (Outstanding Principal)*E^(RT) owedTokens in repayment. */ // Outstanding Principal for each bucket mapping(uint256 => uint256) public principalForBucket; // Total Outstanding Principal uint256 public principalTotal; /** * Weight determines an account's proportional share of a bucket. Relative weights have no * meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has * no meaning. However, the relative weight of two accounts within the same bucket is equal to * the accounts' shares in the bucket and are therefore proportional to the payout that they * should expect from withdrawing from that bucket. */ // Weight for each account in each bucket mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount; // Total Weight for each bucket mapping(uint256 => uint256) public weightForBucket; /** * The critical bucket is: * - Greater-than-or-equal-to The highest bucket with Outstanding Principal * - Less-than-or-equal-to the lowest bucket with Available Amount * * It is equal to both of these values in most cases except in an edge cases where the two * buckets are different. This value is cached to find such a bucket faster than looping through * all possible buckets. */ uint256 public criticalBucket = 0; /** * Latest cached value for totalOwedTokenRepaidToLender. * This number updates on the dYdX Margin base protocol whenever the position is * partially-closed, but this contract is not notified at that time. Therefore, it is updated * upon increasing the position or when depositing/withdrawing */ uint256 public cachedRepaidAmount = 0; // True if the position was closed from force-recovering the collateral bool public wasForceClosed = false; // ============ Constants ============ // Unique ID of the position bytes32 public POSITION_ID; // Address of the token held in the position as collateral address public HELD_TOKEN; // Address of the token being lent address public OWED_TOKEN; // Time between new buckets uint32 public BUCKET_TIME; // Interest rate of the position uint32 public INTEREST_RATE; // Interest period of the position uint32 public INTEREST_PERIOD; // Maximum duration of the position uint32 public MAX_DURATION; // Margin-call time-limit of the position uint32 public CALL_TIMELIMIT; // (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position uint32 public MIN_HELD_TOKEN_NUMERATOR; uint32 public MIN_HELD_TOKEN_DENOMINATOR; // Accounts that are permitted to margin-call positions (or cancel the margin call) mapping(address => bool) public TRUSTED_MARGIN_CALLERS; // Accounts that are permitted to withdraw on behalf of any address mapping(address => bool) public TRUSTED_WITHDRAWERS; // ============ Constructor ============ constructor( address margin, bytes32 positionId, address heldToken, address owedToken, uint32[7] parameters, address[] trustedMarginCallers, address[] trustedWithdrawers ) public OnlyMargin(margin) { POSITION_ID = positionId; HELD_TOKEN = heldToken; OWED_TOKEN = owedToken; require( parameters[0] != 0, "BucketLender#constructor: BUCKET_TIME cannot be zero" ); BUCKET_TIME = parameters[0]; INTEREST_RATE = parameters[1]; INTEREST_PERIOD = parameters[2]; MAX_DURATION = parameters[3]; CALL_TIMELIMIT = parameters[4]; MIN_HELD_TOKEN_NUMERATOR = parameters[5]; MIN_HELD_TOKEN_DENOMINATOR = parameters[6]; // Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS uint256 i = 0; for (i = 0; i < trustedMarginCallers.length; i++) { TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true; } for (i = 0; i < trustedWithdrawers.length; i++) { TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true; } // Set maximum allowance on proxy OWED_TOKEN.approve( Margin(margin).getTokenProxyAddress(), MathHelpers.maxUint256() ); } // ============ Modifiers ============ modifier onlyPosition(bytes32 positionId) { require( POSITION_ID == positionId, "BucketLender#onlyPosition: Incorrect position" ); _; } // ============ Margin-Only State-Changing Functions ============ /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * @param addresses Loan offering addresses * @param values256 Loan offering uint256s * @param values32 Loan offering uint32s * @param positionId Unique ID of the position * @param signature Arbitrary bytes * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( Margin(DYDX_MARGIN).containsPosition(POSITION_ID), "BucketLender#verifyLoanOffering: This contract should not open a new position" ); MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32, signature ); // CHECK ADDRESSES assert(loanOffering.owedToken == OWED_TOKEN); assert(loanOffering.heldToken == HELD_TOKEN); assert(loanOffering.payer == address(this)); assert(loanOffering.owner == address(this)); require( loanOffering.taker == address(0), "BucketLender#verifyLoanOffering: loanOffering.taker is non-zero" ); require( loanOffering.feeRecipient == address(0), "BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero" ); require( loanOffering.positionOwner == address(0), "BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero" ); require( loanOffering.lenderFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero" ); require( loanOffering.takerFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero" ); // CHECK VALUES256 require( loanOffering.rates.maxAmount == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect" ); require( loanOffering.rates.minAmount == 0, "BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero" ); require( loanOffering.rates.minHeldToken == 0, "BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero" ); require( loanOffering.rates.lenderFee == 0, "BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero" ); require( loanOffering.rates.takerFee == 0, "BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero" ); require( loanOffering.expirationTimestamp == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: expirationTimestamp is incorrect" ); require( loanOffering.salt == 0, "BucketLender#verifyLoanOffering: loanOffering.salt is non-zero" ); // CHECK VALUES32 require( loanOffering.callTimeLimit == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect" ); require( loanOffering.maxDuration == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect" ); assert(loanOffering.rates.interestRate == INTEREST_RATE); assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD); // no need to require anything about loanOffering.signature return address(this); } /** * Called by the Margin contract when anyone transfers ownership of a loan to this contract. * This function initializes this contract and returns this address to indicate to Margin * that it is willing to take ownership of the loan. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address on success, throw otherwise */ function receiveLoanOwnership( address from, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID); uint256 initialPrincipal = position.principal; uint256 minHeldToken = MathHelpers.getPartialAmount( uint256(MIN_HELD_TOKEN_NUMERATOR), uint256(MIN_HELD_TOKEN_DENOMINATOR), initialPrincipal ); assert(initialPrincipal > 0); assert(principalTotal == 0); assert(from != address(this)); // position must be opened without lending from this position require( position.owedToken == OWED_TOKEN, "BucketLender#receiveLoanOwnership: Position owedToken mismatch" ); require( position.heldToken == HELD_TOKEN, "BucketLender#receiveLoanOwnership: Position heldToken mismatch" ); require( position.maxDuration == MAX_DURATION, "BucketLender#receiveLoanOwnership: Position maxDuration mismatch" ); require( position.callTimeLimit == CALL_TIMELIMIT, "BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch" ); require( position.interestRate == INTEREST_RATE, "BucketLender#receiveLoanOwnership: Position interestRate mismatch" ); require( position.interestPeriod == INTEREST_PERIOD, "BucketLender#receiveLoanOwnership: Position interestPeriod mismatch" ); require( Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken, "BucketLender#receiveLoanOwnership: Not enough heldToken as collateral" ); // set relevant constants principalForBucket[0] = initialPrincipal; principalTotal = initialPrincipal; weightForBucket[0] = weightForBucket[0].add(initialPrincipal); weightForBucketForAccount[0][from] = weightForBucketForAccount[0][from].add(initialPrincipal); return address(this); } /** * Called by Margin when additional value is added onto the position this contract * is lending for. Balance is added to the address that loaned the additional tokens. * * @param payer Address that loaned the additional tokens * @param positionId Unique ID of the position * @param principalAdded Amount that was added to the position * @param lentAmount Amount of owedToken lent * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { Margin margin = Margin(DYDX_MARGIN); require( payer == address(this), "BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position" ); require( !margin.isPositionCalled(POSITION_ID), "BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called" ); // This function is only called after the state has been updated in the base protocol; // thus, the principal in the base protocol will equal the principal after the increase uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID); uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded); // principalTotal was the principal after the previous increase accountForClose(principalTotal.sub(principalBeforeIncrease)); accountForIncrease(principalAdded, lentAmount); assert(principalTotal == principalAfterIncrease); return address(this); } /** * Function a contract must implement in order to let other addresses call marginCall(). * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[caller], "BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted" ); require( depositAmount == 0, // prevents depositing from canceling the margin-call "BucketLender#marginCallOnBehalfOf: Deposit amount must be zero" ); return address(this); } /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[canceler], "BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted" ); return address(this); } /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address /* recoverer */, bytes32 positionId, address recipient ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { return forceRecoverCollateralInternal(recipient); } // ============ Public State-Changing Functions ============ /** * Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if * part of the position has been closed since the last position increase. */ function rebalanceBuckets() external nonReentrant { rebalanceBucketsInternal(); } /** * Allows users to deposit owedToken into this contract. Allowance must be set on this contract * for "token" in at least the amount "amount". * * @param beneficiary The account that will be entitled to this depoit * @param amount The amount of owedToken to deposit * @return The bucket number that was deposited into */ function deposit( address beneficiary, uint256 amount ) external nonReentrant returns (uint256) { Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; require( beneficiary != address(0), "BucketLender#deposit: Beneficiary cannot be the zero address" ); require( amount != 0, "BucketLender#deposit: Cannot deposit zero tokens" ); require( !margin.isPositionClosed(positionId), "BucketLender#deposit: Cannot deposit after the position is closed" ); require( !margin.isPositionCalled(positionId), "BucketLender#deposit: Cannot deposit while the position is margin-called" ); rebalanceBucketsInternal(); OWED_TOKEN.transferFrom( msg.sender, address(this), amount ); uint256 bucket = getCurrentBucket(); uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket)); uint256 weightToAdd = 0; if (effectiveAmount == 0) { weightToAdd = amount; // first deposit in bucket } else { weightToAdd = MathHelpers.getPartialAmount( amount, effectiveAmount, weightForBucket[bucket] ); } require( weightToAdd != 0, "BucketLender#deposit: Cannot deposit for zero weight" ); // update state updateAvailable(bucket, amount, true); weightForBucketForAccount[bucket][beneficiary] = weightForBucketForAccount[bucket][beneficiary].add(weightToAdd); weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd); emit Deposit( beneficiary, bucket, amount, weightToAdd ); return bucket; } /** * Allows users to withdraw their lent funds. An account can withdraw its weighted share of the * bucket. * * While the position is open, a bucket's share is equal to: * Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest) * Held Token: 0 * * After the position is closed, a bucket's share is equal to: * Owed Token: (Available Amount) * Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal) * * @param buckets The bucket numbers to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens * withdrawn will be at least this amount, but not necessarily more. * Withdrawing the same weight from different buckets does not necessarily * return the same amounts from those buckets. In order to withdraw as many * tokens as possible, use the maximum uint256. * @param onBehalfOf The address to withdraw on behalf of * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdraw( uint256[] buckets, uint256[] maxWeights, address onBehalfOf ) external nonReentrant returns (uint256, uint256) { require( buckets.length == maxWeights.length, "BucketLender#withdraw: The lengths of the input arrays must match" ); if (onBehalfOf != msg.sender) { require( TRUSTED_WITHDRAWERS[msg.sender], "BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others" ); } rebalanceBucketsInternal(); // decide if some bucket is unable to be withdrawn from (is locked) // the zero value represents no-lock uint256 lockedBucket = 0; if ( Margin(DYDX_MARGIN).containsPosition(POSITION_ID) && criticalBucket == getCurrentBucket() ) { lockedBucket = criticalBucket; } uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken uint256 maxHeldToken = 0; if (wasForceClosed) { maxHeldToken = HELD_TOKEN.balanceOf(address(this)); } for (uint256 i = 0; i < buckets.length; i++) { uint256 bucket = buckets[i]; // prevent withdrawing from the current bucket if it is also the critical bucket if ((bucket != 0) && (bucket == lockedBucket)) { continue; } (uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket( onBehalfOf, bucket, maxWeights[i], maxHeldToken ); results[0] = results[0].add(owedTokenForBucket); results[1] = results[1].add(heldTokenForBucket); } // Transfer share of owedToken OWED_TOKEN.transfer(msg.sender, results[0]); HELD_TOKEN.transfer(msg.sender, results[1]); return (results[0], results[1]); } /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to this contract by calling * deposit() will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { rebalanceBucketsInternal(); uint256 amount = token.balanceOf(address(this)); if (token == OWED_TOKEN) { amount = amount.sub(availableTotal); } else if (token == HELD_TOKEN) { require( !wasForceClosed, "BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed" ); } token.transfer(to, amount); return amount; } // ============ Public Getter Functions ============ /** * Get the current bucket number that funds will be deposited into. This is also the highest * bucket so far. * * @return The highest bucket and the one that funds will be deposited into */ function getCurrentBucket() public view returns (uint256) { // load variables from storage; Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; uint32 bucketTime = BUCKET_TIME; assert(!margin.isPositionClosed(positionId)); // if position not created, allow deposits in the first bucket if (!margin.containsPosition(positionId)) { return 0; } // return the number of BUCKET_TIME periods elapsed since the position start, rounded-up uint256 startTimestamp = margin.getPositionStartTimestamp(positionId); return block.timestamp.sub(startTimestamp).div(bucketTime).add(1); } /** * Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of * the bucket multiplied by the interest accrued in the position. If the position is closed, * then any outstanding principal will never be repaid in the form of owedToken. * * @param bucket The bucket number * @return The amount of owedToken that this bucket expects to be paid-back if the posi */ function getBucketOwedAmount( uint256 bucket ) public view returns (uint256) { // if the position is completely closed, then the outstanding principal will never be repaid if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) { return 0; } uint256 lentPrincipal = principalForBucket[bucket]; // the bucket has no outstanding principal if (lentPrincipal == 0) { return 0; } // get the total amount of owedToken that would be paid back at this time uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime( POSITION_ID, principalTotal, uint32(block.timestamp) ); // return the bucket's share return MathHelpers.getPartialAmount( lentPrincipal, principalTotal, owedAmount ); } // ============ Internal Functions ============ function forceRecoverCollateralInternal( address recipient ) internal returns (address) { require( recipient == address(this), "BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract" ); rebalanceBucketsInternal(); wasForceClosed = true; return address(this); } // ============ Private Helper Functions ============ /** * Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the * state if part of the position has been closed since the last position increase. */ function rebalanceBucketsInternal() private { // if force-closed, don't update the outstanding principal values; they are needed to repay // lenders with heldToken if (wasForceClosed) { return; } uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID); accountForClose(principalTotal.sub(marginPrincipal)); assert(principalTotal == marginPrincipal); } /** * Updates the state variables at any time. Only does anything after the position has been * closed or partially-closed since the last time this function was called. * * - Increases the available amount in the highest buckets with outstanding principal * - Decreases the principal amount in those buckets * * @param principalRemoved Amount of principal closed since the last update */ function accountForClose( uint256 principalRemoved ) private { if (principalRemoved == 0) { return; } uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID); assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved); uint256 principalToSub = principalRemoved; uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount); uint256 criticalBucketTemp = criticalBucket; // loop over buckets in reverse order starting with the critical bucket for ( uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { assert(bucket <= criticalBucketTemp); // no underflow on bucket uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue; } uint256 availableTemp = MathHelpers.getPartialAmount( principalTemp, principalToSub, availableToAdd ); updateAvailable(bucket, availableTemp, true); updatePrincipal(bucket, principalTemp, false); principalToSub = principalToSub.sub(principalTemp); availableToAdd = availableToAdd.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToSub == 0); assert(availableToAdd == 0); setCriticalBucket(criticalBucketTemp); cachedRepaidAmount = newRepaidAmount; } /** * Updates the state variables when a position is increased. * * - Decreases the available amount in the lowest buckets with available token * - Increases the principal amount in those buckets * * @param principalAdded Amount of principal added to the position * @param lentAmount Amount of owedToken lent */ function accountForIncrease( uint256 principalAdded, uint256 lentAmount ) private { require( lentAmount <= availableTotal, "BucketLender#accountForIncrease: No lending not-accounted-for funds" ); uint256 principalToAdd = principalAdded; uint256 availableToSub = lentAmount; uint256 criticalBucketTemp; // loop over buckets in order starting from the critical bucket uint256 lastBucket = getCurrentBucket(); for ( uint256 bucket = criticalBucket; principalToAdd > 0; bucket++ ) { assert(bucket <= lastBucket); // should never go past the last bucket uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]); if (availableTemp == 0) { continue; } uint256 principalTemp = MathHelpers.getPartialAmount( availableTemp, availableToSub, principalToAdd ); updateAvailable(bucket, availableTemp, false); updatePrincipal(bucket, principalTemp, true); principalToAdd = principalToAdd.sub(principalTemp); availableToSub = availableToSub.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToAdd == 0); assert(availableToSub == 0); setCriticalBucket(criticalBucketTemp); } /** * Withdraw * * @param onBehalfOf The account for which to withdraw for * @param bucket The bucket number to withdraw from * @param maxWeight The maximum weight to withdraw * @param maxHeldToken The total amount of heldToken that has been force-recovered * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdrawSingleBucket( address onBehalfOf, uint256 bucket, uint256 maxWeight, uint256 maxHeldToken ) private returns (uint256, uint256) { // calculate the user's share uint256 bucketWeight = weightForBucket[bucket]; if (bucketWeight == 0) { return (0, 0); } uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf]; uint256 weightToWithdraw = Math.min256(maxWeight, userWeight); if (weightToWithdraw == 0) { return (0, 0); } // update state weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw); weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw); // calculate for owedToken uint256 owedTokenToWithdraw = withdrawOwedToken( bucket, weightToWithdraw, bucketWeight ); // calculate for heldToken uint256 heldTokenToWithdraw = withdrawHeldToken( bucket, weightToWithdraw, bucketWeight, maxHeldToken ); emit Withdraw( onBehalfOf, bucket, weightToWithdraw, owedTokenToWithdraw, heldTokenToWithdraw ); return (owedTokenToWithdraw, heldTokenToWithdraw); } /** * Helper function to withdraw earned owedToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @return The amount of owedToken being withdrawn */ function withdrawOwedToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight ) private returns (uint256) { // amount to return for the bucket uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount( userWeight, bucketWeight, availableForBucket[bucket].add(getBucketOwedAmount(bucket)) ); // check that there is enough token to give back require( owedTokenToWithdraw <= availableForBucket[bucket], "BucketLender#withdrawOwedToken: There must be enough available owedToken" ); // update amounts updateAvailable(bucket, owedTokenToWithdraw, false); return owedTokenToWithdraw; } /** * Helper function to withdraw heldToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @param maxHeldToken The total amount of heldToken available to withdraw * @return The amount of heldToken being withdrawn */ function withdrawHeldToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight, uint256 maxHeldToken ) private returns (uint256) { if (maxHeldToken == 0) { return 0; } // user's principal for the bucket uint256 principalForBucketForAccount = MathHelpers.getPartialAmount( userWeight, bucketWeight, principalForBucket[bucket] ); uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount( principalForBucketForAccount, principalTotal, maxHeldToken ); updatePrincipal(bucket, principalForBucketForAccount, false); return heldTokenToWithdraw; } // ============ Setter Functions ============ /** * Changes the critical bucket variable * * @param bucket The value to set criticalBucket to */ function setCriticalBucket( uint256 bucket ) private { // don't spend the gas to sstore unless we need to change the value if (criticalBucket == bucket) { return; } criticalBucket = bucket; } /** * Changes the available owedToken amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the available amount by * @param increase True if positive change, false if negative change */ function updateAvailable( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = availableTotal.add(amount); newForBucket = availableForBucket[bucket].add(amount); emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = availableTotal.sub(amount); newForBucket = availableForBucket[bucket].sub(amount); emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } availableTotal = newTotal; availableForBucket[bucket] = newForBucket; } /** * Changes the principal amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the principal amount by * @param increase True if positive change, false if negative change */ function updatePrincipal( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = principalTotal.add(amount); newForBucket = principalForBucket[bucket].add(amount); emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = principalTotal.sub(amount); newForBucket = principalForBucket[bucket].sub(amount); emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } principalTotal = newTotal; principalForBucket[bucket] = newForBucket; } } // File: contracts/margin/external/BucketLender/BucketLenderFactory.sol /** * @title BucketLenderFactory * @author dYdX * * Contract that allows anyone to deploy a BucketLender contract by sending a transaction. */ contract BucketLenderFactory { // ============ Events ============ event BucketLenderCreated( address indexed creator, address indexed owner, bytes32 indexed positionId, address at ); // ============ State Variables ============ // Address of the Margin contract for the dYdX Margin Trading Protocol address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Public Functions ============ /** * Deploy a new BucketLender contract to the blockchain * * @param positionId Unique ID of the position * @param owner Address to which ownership of the BucketLender will be transferred * @param heldToken Address of the token held in the position as collateral * @param owedToken Address of the token being lent by the BucketLender * @param parameters Values corresponding to: * * [0] = number of seconds per bucket * [1] = interest rate * [2] = interest period * [3] = maximum loan duration * [4] = margin-call timelimit * [5] = numerator of minimum heldToken-per-owedToken * [6] = denominator of minimum heldToken-per-owedToken * * @param marginCallers Accounts that are permitted to margin-call positions (or cancel the margin call) * @return The address of the new BucketLender contract */ function createBucketLender( bytes32 positionId, address owner, address heldToken, address owedToken, uint32[7] parameters, address[] marginCallers, address[] withdrawers ) external returns (address) { address newBucketLender = new BucketLender( DYDX_MARGIN, positionId, heldToken, owedToken, parameters, marginCallers, withdrawers ); BucketLender(newBucketLender).transferOwnership(owner); emit BucketLenderCreated( msg.sender, owner, positionId, newBucketLender ); return newBucketLender; } }
Gets if a position is currently margin-called. positionId Unique ID of the position return True if the position is margin-called/
function isPositionCalled( bytes32 positionId ) external view returns (bool) { return (state.positions[positionId].callTimestamp > 0); }
1,594,124
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol
Create store user information (db) addr user address code user invite Code rCode recommend code/
function _registerUser(address addr, string memory code, string memory rCode) internal { db.registerUser(addr, code, rCode); }
8,114,052
./partial_match/1/0xF0a707dad7F2448dFB2B9D85BED522A6CbbfAE13/sources/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol
Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way./
function _tryGetAssetDecimals(IERC20Upgradeable asset_) private view returns (bool, uint8) { (bool success, bytes memory encodedDecimals) = address(asset_).staticcall( abi.encodeWithSelector(IERC20MetadataUpgradeable.decimals.selector) ); if (success && encodedDecimals.length >= 32) { uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256)); if (returnedDecimals <= type(uint8).max) { return (true, uint8(returnedDecimals)); } } return (false, 0); }
3,906,782
/** *Submitted for verification at Etherscan.io on 2020-09-18 */ /** *Submitted for verification at Etherscan.io on 2020-09-18 */ // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol pragma solidity 0.5.7; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/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 ); } // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity 0.5.7; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: nexusmutual-contracts/contracts/NXMToken.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract NXMToken is IERC20 { using SafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @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 returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @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 canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @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) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @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 ) internal { _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); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns(uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMaster { function getLatestAddress(bytes2 _module) public view returns(address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: nexusmutual-contracts/contracts/INXMMaster.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns(bool); function isInternal(address _add) public view returns(bool); function isPause() public view returns(bool check); function isOwner(address _add) public view returns(bool); function isMember(address _add) public view returns(bool); function checkIsAuthToGoverned(address _add) public view returns(bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns(address _add); function dAppToken() public view returns(address _add); function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress); } // File: nexusmutual-contracts/contracts/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } // File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol pragma solidity ^0.5.7; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } // File: nexusmutual-contracts/contracts/TokenFunctions.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenFunctions is Iupgradable { using SafeMath for uint; MCR internal m1; MemberRoles internal mr; NXMToken public tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; PoolData internal pd; IPooledStaking pooledStaking; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev Rewards stakers on purchase of cover on smart contract. * @param _contractAddress smart contract address. * @param _coverPriceNXM cover price in NXM. */ function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal { uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100); pooledStaking.accumulateReward(_contractAddress, rewardValue); } /** * @dev Deprecated in favor of burnStakedTokens */ function burnStakerLockedToken(uint, bytes4, uint) external { // noop } /** * @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed. * @param coverId cover id * @param coverCurrency cover currency * @param sumAssured amount of $curr to burn */ function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal { (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = m1.calculateTokenPrice(coverCurrency); uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); } /** * @dev Gets the total staked NXM tokens against * Smart contract by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function deprecated_getTotalStakedTokensOnSmartContract( address _stakedContractAddress ) external view returns(uint) { uint stakedAmount = 0; address stakerAddress; uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress); for (uint i = 0; i < staketLen; i++) { stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i); uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress, _stakedContractAddress, stakerIndex); stakedAmount = stakedAmount.add(currentlyStaked); } return stakedAmount; } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) { return _getUserLockedCNTokens(_of, _coverId); } /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns(uint amount) { for (uint i = 0; i < qd.getUserCoverLength(_of); i++) { amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i])); } } /** * @dev Returns amount of NXM Tokens locked as Cover Note against given coverId. * @param _coverId coverId of the cover. */ function getLockedCNAgainstCover(uint _coverId) external view returns(uint) { return _getLockedCNAgainstCover(_coverId); } /** * @dev Returns total amount of staked NXM Tokens on all smart contracts. * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) { uint stakedAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i); stakedAmount = stakedAmount.add(currentlyStaked); } amount = stakedAmount; } /** * @dev Returns total unlockable amount of staked NXM Tokens on all smart contract . * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllUnlockableStakedTokens( address _stakerAddress ) external view returns (uint amount) { uint unlockableAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = unlockableAmount.add( _deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress, scIndex)); } amount = unlockableAmount; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /** * @dev Gets the Token price in a given currency * @param curr Currency name. * @return price Token Price. */ function getTokenPrice(bytes4 curr) public view returns(uint price) { price = m1.calculateTokenPrice(curr); } /** * @dev Set the flag to check if cover note is deposited against the cover id * @param coverId Cover Id. */ function depositCN(uint coverId) public onlyInternal returns (bool success) { require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available"); td.setDepositCN(coverId, true); success = true; } /** * @param _of address of Member * @param _coverId Cover Id * @param _lockTime Pending Time + Cover Period 7*1 days */ function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal { uint timeStamp = now.add(_lockTime); uint coverValidUntil = qd.getValidityOfCover(_coverId); if (timeStamp >= coverValidUntil) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); tc.extendLockOf(_of, reason, timeStamp); } } /** * @dev to burn the deposited cover tokens * @param coverId is id of cover whose tokens have to be burned * @return the status of the successful burning */ function burnDepositCN(uint coverId) public onlyInternal returns (bool success) { address _of = qd.getCoverMemberAddress(coverId); uint amount; (amount, ) = td.depositedCN(coverId); amount = (amount.mul(50)).div(100); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); tc.burnLockedTokens(_of, reason, amount); success = true; } /** * @dev Unlocks covernote locked against a given cover * @param coverId id of cover */ function unlockCN(uint coverId) public onlyInternal { (, bool isDeposited) = td.depositedCN(coverId); require(!isDeposited,"Cover note is deposited and can not be released"); uint lockedCN = _getLockedCNAgainstCover(coverId); if (lockedCN != 0) { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) public { require(ms.checkIsAuthToGoverned(msg.sender)); tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to lock cover note tokens * @param coverNoteAmount is number of tokens to be locked * @param coverPeriod is cover period in concern * @param coverId is the cover id of cover in concern * @param _of address whose tokens are to be locked */ function lockCN( uint coverNoteAmount, uint coverPeriod, uint coverId, address _of ) public onlyInternal { uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp()); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); td.setDepositCNAmount(coverId, coverNoteAmount); tc.lockOf(_of, reason, coverNoteAmount, validity); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns(bool) { return now < tk.isLockedForMV(_of); } /** * @dev Internal function to gets amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress, _stakedContractAddress, _stakedContractIndex); } /** * @dev Function to gets unlockable amount of locked NXM * tokens, staked against smartcontract by index * @param stakerAddress address of staker * @param stakedContractAddress staked contract address * @param stakerIndex index of staking */ function deprecated_getStakerUnlockableTokensOnSmartContract ( address stakerAddress, address stakedContractAddress, uint stakerIndex ) public view returns (uint) { return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress, td.getStakerStakedContractIndex(stakerAddress, stakerIndex)); } /** * @dev releases unlockable staked tokens to staker */ function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause { uint unlockableAmount; address scAddress; bytes32 reason; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract( _stakerAddress, scAddress, scIndex); td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0); td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount); reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex)); tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount); } } /** * @dev to get tokens of staker locked before burning that are allowed to burn * @param stakerAdd is the address of the staker * @param stakedAdd is the address of staked contract in concern * @param stakerIndex is the staker index in concern * @return amount of unlockable tokens * @return amount of tokens that can burn */ function _deprecated_unlockableBeforeBurningAndCanBurn( address stakerAdd, address stakedAdd, uint stakerIndex ) public view returns (uint amount, uint canBurn) { uint dateAdd; uint initialStake; uint totalBurnt; uint ub; (, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex); canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays()); // Can't use SafeMaths for int. int v = int(initialStake - (canBurn) - (totalBurnt) - ( td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub)); uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract( stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex)); if (v < 0) { v = 0; } amount = uint(v); if (canBurn > currentLockedTokens.sub(amount).sub(ub)) { canBurn = currentLockedTokens.sub(amount).sub(ub); } } /** * @dev to get tokens of staker that are unlockable * @param _stakerAddress is the address of the staker * @param _stakedContractAddress is the address of staked contract in concern * @param _stakedContractIndex is the staked contract index in concern * @return amount of unlockable tokens */ function _deprecated_getStakerUnlockableTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { uint initialStake; uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); uint burnt; (, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex); uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex); uint currentStakedTokens; (, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, _stakedContractAddress, stakerIndex); amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt); } /** * @dev Internal function to get the amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function _deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) internal view returns (uint amount) { bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); amount = tc.tokensLocked(_stakerAddress, reason); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _coverId coverId of the cover. */ function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) { address coverHolder = qd.getCoverMemberAddress(_coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId)); return tc.tokensLockedAtTime(coverHolder, reason, now); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); return tc.tokensLockedAtTime(_of, reason, now); } /** * @dev Internal function to gets remaining amount of staked NXM tokens, * against smartcontract by index * @param _stakeAmount address of user * @param _stakeDays staked contract address * @param _validDays index of staking */ function _deprecated_calculateStakedTokens( uint _stakeAmount, uint _stakeDays, uint _validDays ) internal pure returns (uint amount) { if (_validDays > _stakeDays) { uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays); amount = (rf.mul(_stakeAmount)).div(100000); } else { amount = 0; } } /** * @dev Gets the total staked NXM tokens against Smart contract * by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function _deprecated_burnStakerTokenLockedAgainstSmartContract( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _amount ) internal { uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount); bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); tc.burnLockedTokens(_stakerAddress, reason, _amount); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMemberRoles { event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public; /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(address _memberAddress, uint _roleId, bool _active) public; /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _authorized New authorized address against role id function changeAuthorized(uint _roleId, address _authorized) public; /// @dev Return number of member roles function totalRoles() public view returns(uint256); /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress); /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberAddress.length Member length function numberOfMembers(uint _memberRoleId) public view returns(uint); /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address); /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory assignedRoles); /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool); } // File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol pragma solidity 0.5.7; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract IERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: nexusmutual-contracts/contracts/TokenController.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenController is IERC1132, Iupgradable { using SafeMath for uint256; event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime = uint(30).mul(1 days); bytes32 private constant CLA = bytes32("CLA"); /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress('PS')); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) { require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address"); require(token.operatorTransfer(_from, _value), "Operator transfer failed"); require(token.transfer(_to, _value), "Internal transfer failed"); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(minCALockTime <= _time,"Should lock for minimum time"); // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(msg.sender, _reason, _amount, _time); return true; } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Extends lock for reason CLA for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); _extendLock(msg.sender, _reason, _time); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(_tokensLocked(msg.sender, _reason) > 0); token.operatorTransfer(msg.sender, _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity); return true; } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom (address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the unlockable tokens against CLA of a specified address * @param _of Address of user, claiming back unlockable tokens against CLA */ function unlock(address _of) public checkPause returns (uint256 unlockableTokens) { unlockableTokens = _tokensUnlockable(_of, CLA); if (unlockableTokens > 0) { locked[_of][CLA].claimed = true; emit Unlocked(_of, CLA, unlockableTokens); require(token.transfer(_of, unlockableTokens)); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MNCLT") { minCALockTime = val.mul(1 days); } else { revert("Invalid param code"); } } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total locked tokens at time * Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility * for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. * Does not take into account pending burns. * * @param _of member whose locked tokens are to be calculate * @param _time timestamp when the tokens should be locked */ function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time)); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0); require(_amount != 0); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } require(token.operatorTransfer(_of, _amount)); uint256 validUntil = now.add(_time); //solhint-disable-line locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } require(token.transfer(_of, _amount)); emit Unlocked(_of, _reason, _amount); } function _removeReason(address _of, bytes32 _reason) internal { uint len = lockReason[_of].length; for (uint i = 0; i < len; i++) { if (lockReason[_of][i] == _reason) { lockReason[_of][i] = lockReason[_of][len.sub(1)]; lockReason[_of].pop(); break; } } } } // File: nexusmutual-contracts/contracts/ClaimsData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } // File: nexusmutual-contracts/contracts/PoolData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract DSValue { function peek() public view returns (bytes32, bool); function read() public view returns (bytes32); } contract PoolData is Iupgradable { using SafeMath for uint; struct ApiId { bytes4 typeOf; bytes4 currency; uint id; uint64 dateAdd; uint64 dateUpd; } struct CurrencyAssets { address currAddress; uint baseMin; uint varMin; } struct InvestmentAssets { address currAddress; bool status; uint64 minHoldingPercX100; uint64 maxHoldingPercX100; uint8 decimals; } struct IARankDetails { bytes4 maxIACurr; uint64 maxRate; bytes4 minIACurr; uint64 minRate; } struct McrData { uint mcrPercx100; uint mcrEther; uint vFull; //Pool funds uint64 date; } IARankDetails[] internal allIARankDetails; McrData[] public allMCRData; bytes4[] internal allInvestmentCurrencies; bytes4[] internal allCurrencies; bytes32[] public allAPIcall; mapping(bytes32 => ApiId) public allAPIid; mapping(uint64 => uint) internal datewiseId; mapping(bytes16 => uint) internal currencyLastIndex; mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets; mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets; mapping(bytes4 => uint) internal caAvgRate; mapping(bytes4 => uint) internal iaAvgRate; address public notariseMCR; address public daiFeedAddress; uint private constant DECIMAL1E18 = uint(10) ** 18; uint public uniswapDeadline; uint public liquidityTradeCallbackTime; uint public lastLiquidityTradeTrigger; uint64 internal lastDate; uint public variationPercX100; uint public iaRatesTime; uint public minCap; uint public mcrTime; uint public a; uint public shockParameter; uint public c; uint public mcrFailTime; uint public ethVolumeLimit; uint public capReached; uint public capacityLimit; constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public { notariseMCR = _notariseAdd; daiFeedAddress = _daiFeedAdd; c = 5800000; a = 1028; mcrTime = 24 hours; mcrFailTime = 6 hours; allMCRData.push(McrData(0, 0, 0, 0)); minCap = 12000 * DECIMAL1E18; shockParameter = 50; variationPercX100 = 100; //1% iaRatesTime = 24 hours; //24 hours in seconds uniswapDeadline = 20 minutes; liquidityTradeCallbackTime = 4 hours; ethVolumeLimit = 4; capacityLimit = 10; allCurrencies.push("ETH"); allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0); allCurrencies.push("DAI"); allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0); allInvestmentCurrencies.push("ETH"); allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18); allInvestmentCurrencies.push("DAI"); allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18); } /** * @dev to set the maximum cap allowed * @param val is the new value */ function setCapReached(uint val) external onlyInternal { capReached = val; } /// @dev Updates the 3 day average rate of a IA currency. /// To be replaced by MakerDao's on chain rates /// @param curr IA Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal { iaAvgRate[curr] = rate; } /// @dev Updates the 3 day average rate of a CA currency. /// To be replaced by MakerDao's on chain rates /// @param curr Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal { caAvgRate[curr] = rate; } /// @dev Adds details of (Minimum Capital Requirement)MCR. /// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456) /// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model. function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal { allMCRData.push(McrData(mcrp, mcre, vf, time)); } /** * @dev Updates the Timestamp at which result of oracalize call is received. */ function updateDateUpdOfAPI(bytes32 myid) external onlyInternal { allAPIid[myid].dateUpd = uint64(now); } /** * @dev Saves the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal,quote,cover etc. for which oraclize call is made */ function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal { allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now)); } /** * @dev Stores the id return by the oraclize query. * Maintains record of all the Ids return by oraclize query. * @param myid Id return by the oraclize query. */ function addInAllApiCall(bytes32 myid) external onlyInternal { allAPIcall.push(myid); } /** * @dev Saves investment asset rank details. * @param maxIACurr Maximum ranked investment asset currency. * @param maxRate Maximum ranked investment asset rate. * @param minIACurr Minimum ranked investment asset currency. * @param minRate Minimum ranked investment asset rate. * @param date in yyyymmdd. */ function saveIARankDetails( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate, uint64 date ) external onlyInternal { allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate)); datewiseId[date] = allIARankDetails.length.sub(1); } /** * @dev to get the time for the laste liquidity trade trigger */ function setLastLiquidityTradeTrigger() external onlyInternal { lastLiquidityTradeTrigger = now; } /** * @dev Updates Last Date. */ function updatelastDate(uint64 newDate) external onlyInternal { lastDate = newDate; } /** * @dev Adds currency asset currency. * @param curr currency of the asset * @param currAddress address of the currency * @param baseMin base minimum in 10^18. */ function addCurrencyAssetCurrency( bytes4 curr, address currAddress, uint baseMin ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencies.push(curr); allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0); } /** * @dev Adds investment asset. */ function addInvestmentAssetCurrency( bytes4 curr, address currAddress, bool status, uint64 minHoldingPercX100, uint64 maxHoldingPercX100, uint8 decimals ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentCurrencies.push(curr); allInvestmentAssets[curr] = InvestmentAssets(currAddress, status, minHoldingPercX100, maxHoldingPercX100, decimals); } /** * @dev Changes base minimum of a given currency asset. */ function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].baseMin = baseMin; } /** * @dev changes variable minimum of a given currency asset. */ function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal { allCurrencyAssets[curr].varMin = varMin; } /** * @dev Changes the investment asset status. */ function changeInvestmentAssetStatus(bytes4 curr, bool status) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].status = status; } /** * @dev Changes the investment asset Holding percentage of a given currency. */ function changeInvestmentAssetHoldingPerc( bytes4 curr, uint64 minPercX100, uint64 maxPercX100 ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].minHoldingPercX100 = minPercX100; allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100; } /** * @dev Gets Currency asset token address. */ function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].currAddress = currAdd; } /** * @dev Changes Investment asset token address. */ function changeInvestmentAssetAddressAndDecimal( bytes4 curr, address currAdd, uint8 newDecimal ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].currAddress = currAdd; allInvestmentAssets[curr].decimals = newDecimal; } /// @dev Changes address allowed to post MCR. function changeNotariseAddress(address _add) external onlyInternal { notariseMCR = _add; } /// @dev updates daiFeedAddress address. /// @param _add address of DAI feed. function changeDAIfeedAddress(address _add) external onlyInternal { daiFeedAddress = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "MCRTIM") { val = mcrTime / (1 hours); } else if (code == "MCRFTIM") { val = mcrFailTime / (1 hours); } else if (code == "MCRMIN") { val = minCap; } else if (code == "MCRSHOCK") { val = shockParameter; } else if (code == "MCRCAPL") { val = capacityLimit; } else if (code == "IMZ") { val = variationPercX100; } else if (code == "IMRATET") { val = iaRatesTime / (1 hours); } else if (code == "IMUNIDL") { val = uniswapDeadline / (1 minutes); } else if (code == "IMLIQT") { val = liquidityTradeCallbackTime / (1 hours); } else if (code == "IMETHVL") { val = ethVolumeLimit; } else if (code == "C") { val = c; } else if (code == "A") { val = a; } } /// @dev Checks whether a given address can notaise MCR data or not. /// @param _add Address. /// @return res Returns 0 if address is not authorized, else 1. function isnotarise(address _add) external view returns(bool res) { res = false; if (_add == notariseMCR) res = true; } /// @dev Gets the details of last added MCR. /// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100). /// @return vFull Total Pool fund value in Ether used in the last full daily calculation. function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) { uint index = allMCRData.length.sub(1); return ( allMCRData[index].mcrPercx100, allMCRData[index].mcrEther, allMCRData[index].vFull, allMCRData[index].date ); } /// @dev Gets last Minimum Capital Requirement percentage of Capital Model /// @return val MCR% value,multiplied by 100. function getLastMCRPerc() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrPercx100; } /// @dev Gets last Ether price of Capital Model /// @return val ether value,multiplied by 100. function getLastMCREther() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrEther; } /// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model. function getLastVfull() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].vFull; } /// @dev Gets last Minimum Capital Requirement in Ether. /// @return date of MCR. function getLastMCRDate() external view returns(uint64 date) { date = allMCRData[allMCRData.length.sub(1)].date; } /// @dev Gets details for token price calculation. function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) { _a = a; _c = c; rate = _getAvgRate(curr, false); } /// @dev Gets the total number of times MCR calculation has been made. function getMCRDataLength() external view returns(uint len) { len = allMCRData.length; } /** * @dev Gets investment asset rank details by given date. */ function getIARankDetailsByDate( uint64 date ) external view returns( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate ) { uint index = datewiseId[date]; return ( allIARankDetails[index].maxIACurr, allIARankDetails[index].maxRate, allIARankDetails[index].minIACurr, allIARankDetails[index].minRate ); } /** * @dev Gets Last Date. */ function getLastDate() external view returns(uint64 date) { return lastDate; } /** * @dev Gets investment currency for a given index. */ function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) { return allInvestmentCurrencies[index]; } /** * @dev Gets count of investment currency. */ function getInvestmentCurrencyLen() external view returns(uint len) { return allInvestmentCurrencies.length; } /** * @dev Gets all the investment currencies. */ function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) { return allInvestmentCurrencies; } /** * @dev Gets All currency for a given index. */ function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) { return allCurrencies[index]; } /** * @dev Gets count of All currency. */ function getAllCurrenciesLen() external view returns(uint len) { return allCurrencies.length; } /** * @dev Gets all currencies */ function getAllCurrencies() external view returns(bytes4[] memory currencies) { return allCurrencies; } /** * @dev Gets currency asset details for a given currency. */ function getCurrencyAssetVarBase( bytes4 curr ) external view returns( bytes4 currency, uint baseMin, uint varMin ) { return ( curr, allCurrencyAssets[curr].baseMin, allCurrencyAssets[curr].varMin ); } /** * @dev Gets minimum variable value for currency asset. */ function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) { return allCurrencyAssets[curr].varMin; } /** * @dev Gets base minimum of a given currency asset. */ function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) { return allCurrencyAssets[curr].baseMin; } /** * @dev Gets investment asset maximum and minimum holding percentage of a given currency. */ function getInvestmentAssetHoldingPerc( bytes4 curr ) external view returns( uint64 minHoldingPercX100, uint64 maxHoldingPercX100 ) { return ( allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100 ); } /** * @dev Gets investment asset decimals. */ function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) { return allInvestmentAssets[curr].decimals; } /** * @dev Gets investment asset maximum holding percentage of a given currency. */ function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) { return allInvestmentAssets[curr].maxHoldingPercX100; } /** * @dev Gets investment asset minimum holding percentage of a given currency. */ function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) { return allInvestmentAssets[curr].minHoldingPercX100; } /** * @dev Gets investment asset details of a given currency */ function getInvestmentAssetDetails( bytes4 curr ) external view returns( bytes4 currency, address currAddress, bool status, uint64 minHoldingPerc, uint64 maxHoldingPerc, uint8 decimals ) { return ( curr, allInvestmentAssets[curr].currAddress, allInvestmentAssets[curr].status, allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100, allInvestmentAssets[curr].decimals ); } /** * @dev Gets Currency asset token address. */ function getCurrencyAssetAddress(bytes4 curr) external view returns(address) { return allCurrencyAssets[curr].currAddress; } /** * @dev Gets investment asset token address. */ function getInvestmentAssetAddress(bytes4 curr) external view returns(address) { return allInvestmentAssets[curr].currAddress; } /** * @dev Gets investment asset active Status of a given currency. */ function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; } /** * @dev Gets type of oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return _typeof It could be of type "quote","quotation","cover","claim" etc. */ function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].typeOf; } /** * @dev Gets ID associated to oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return id1 It could be the ID of "proposal","quotation","cover","claim" etc. */ function getIdOfApiId(bytes32 myid) external view returns(uint) { return allAPIid[myid].id; } /** * @dev Gets the Timestamp of a oracalize call. */ function getDateAddOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateAdd; } /** * @dev Gets the Timestamp at which result of oracalize call is received. */ function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateUpd; } /** * @dev Gets currency by oracalize id. */ function getCurrOfApiId(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].currency; } /** * @dev Gets ID return by the oraclize query of a given index. * @param index Index. * @return myid ID return by the oraclize query. */ function getApiCallIndex(uint index) external view returns(bytes32 myid) { myid = allAPIcall[index]; } /** * @dev Gets Length of API call. */ function getApilCallLength() external view returns(uint) { return allAPIcall.length; } /** * @dev Get Details of Oraclize API when given Oraclize Id. * @param myid ID return by the oraclize query. * @return _typeof ype of the query for which oraclize * call is made.("proposal","quote","quotation" etc.) */ function getApiCallDetails( bytes32 myid ) external view returns( bytes4 _typeof, bytes4 curr, uint id, uint64 dateAdd, uint64 dateUpd ) { return ( allAPIid[myid].typeOf, allAPIid[myid].currency, allAPIid[myid].id, allAPIid[myid].dateAdd, allAPIid[myid].dateUpd ); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MCRTIM") { _changeMCRTime(val * 1 hours); } else if (code == "MCRFTIM") { _changeMCRFailTime(val * 1 hours); } else if (code == "MCRMIN") { _changeMinCap(val); } else if (code == "MCRSHOCK") { _changeShockParameter(val); } else if (code == "MCRCAPL") { _changeCapacityLimit(val); } else if (code == "IMZ") { _changeVariationPercX100(val); } else if (code == "IMRATET") { _changeIARatesTime(val * 1 hours); } else if (code == "IMUNIDL") { _changeUniswapDeadlineTime(val * 1 minutes); } else if (code == "IMLIQT") { _changeliquidityTradeCallbackTime(val * 1 hours); } else if (code == "IMETHVL") { _setEthVolumeLimit(val); } else if (code == "C") { _changeC(val); } else if (code == "A") { _changeA(val); } else { revert("Invalid param code"); } } /** * @dev to get the average rate of currency rate * @param curr is the currency in concern * @return required rate */ function getCAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, false); } /** * @dev to get the average rate of investment rate * @param curr is the investment in concern * @return required rate */ function getIAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, true); } function changeDependentContractAddress() public onlyInternal {} /// @dev Gets the average rate of a CA currency. /// @param curr Currency Name. /// @return rate Average rate X 100(of last 3 days). function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) { if (curr == "DAI") { DSValue ds = DSValue(daiFeedAddress); rate = uint(ds.read()).div(uint(10) ** 16); } else if (isIA) { rate = iaAvgRate[curr]; } else { rate = caAvgRate[curr]; } } /** * @dev to set the ethereum volume limit * @param val is the new limit value */ function _setEthVolumeLimit(uint val) internal { ethVolumeLimit = val; } /// @dev Sets minimum Cap. function _changeMinCap(uint newCap) internal { minCap = newCap; } /// @dev Sets Shock Parameter. function _changeShockParameter(uint newParam) internal { shockParameter = newParam; } /// @dev Changes time period for obtaining new MCR data from external oracle query. function _changeMCRTime(uint _time) internal { mcrTime = _time; } /// @dev Sets MCR Fail time. function _changeMCRFailTime(uint _time) internal { mcrFailTime = _time; } /** * @dev to change the uniswap deadline time * @param newDeadline is the value */ function _changeUniswapDeadlineTime(uint newDeadline) internal { uniswapDeadline = newDeadline; } /** * @dev to change the liquidity trade call back time * @param newTime is the new value to be set */ function _changeliquidityTradeCallbackTime(uint newTime) internal { liquidityTradeCallbackTime = newTime; } /** * @dev Changes time after which investment asset rates need to be fed. */ function _changeIARatesTime(uint _newTime) internal { iaRatesTime = _newTime; } /** * @dev Changes the variation range percentage. */ function _changeVariationPercX100(uint newPercX100) internal { variationPercX100 = newPercX100; } /// @dev Changes Growth Step function _changeC(uint newC) internal { c = newC; } /// @dev Changes scaling factor. function _changeA(uint val) internal { a = val; } /** * @dev to change the capacity limit * @param val is the new value */ function _changeCapacityLimit(uint val) internal { capacityLimit = val; } } // File: nexusmutual-contracts/contracts/QuotationData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover } enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested } struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns(uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns(address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns(uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns(uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns(uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns(uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns(uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns(uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns(address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } // File: nexusmutual-contracts/contracts/TokenData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public { //solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns(uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns(uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns(bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } // File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol /* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! // Dummy contract only used to emit to end-user they are using wrong solc contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string memory _datasource) public returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice); function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. 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. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } if (address(oraclize) != OAR.getAddress()) { oraclize = OraclizeI(OAR.getAddress()); } _; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { return oraclize_setNetwork(); _networkID; // silence the warning and remain backwards compatible } function oraclize_setNetworkName(string memory _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); oraclize_setNetworkName("eth_goerli"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 _myid, string memory _result) public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public { return; _myid; _result; _proof; // Silence compiler warnings } function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(0, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(_timestamp, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /* END ORACLIZE_API */ // File: nexusmutual-contracts/contracts/Quotation.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Quotation is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; TokenController internal tc; TokenData internal td; Pool1 internal p1; PoolData internal pd; QuotationData internal qd; MCR internal m1; MemberRoles internal mr; bool internal locked; event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); mr = MemberRoles(ms.getLatestAddress("MR")); } function sendEther() public payable { } /** * @dev Expires a cover after a set period of time. * Changes the status of the Cover and reduces the current * sum assured of all areas in which the quotation lies * Unlocks the CN tokens of the cover. Updates the Total Sum Assured value. * @param _cid Cover Id. */ function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); } /** * @dev Checks if a cover should get expired/closed or not. * @param _cid Cover Index. * @return expire true if the Cover's time has expired, false otherwise. */ function checkCoverExpired(uint _cid) public view returns(bool expire) { expire = qd.getValidityOfCover(_cid) < uint64(now); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal { _removeSAFromCSA(_cid, _amount); } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] memory coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) public isMemberAndcheckPause { tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySign( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA, uint8 _v, bytes32 _r, bytes32 _s ) public view returns(bool) { require(smaratCA != address(0)); require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time"); bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA ) public view returns(bytes32) { return keccak256( abi.encodePacked( coverDetails[0], curr, coverPeriod, smaratCA, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev to get the status of recently holded coverID * @param userAdd is the user address in concern * @return the status of the concerned coverId */ function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } } /** * @dev to initiate the membership and the cover * @param smartCAdd is the smart contract address to make cover on * @param coverCurr is the currency used to make cover * @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM * @param coverPeriod is cover period for which cover is being bought * @param _v argument from vrs hash * @param _r argument from vrs hash * @param _s argument from vrs hash */ function initiateMembershipAndCover( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable checkPause { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(!ms.isMember(msg.sender)); require(qd.refundEligible(msg.sender) == false); uint joinFee = td.joiningFee(); uint totalFee = joinFee; if (coverCurr == "ETH") { totalFee = joinFee.add(coverDetails[1]); } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1])); } require(msg.value == totalFee); require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s)); qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod); qd.setRefundEligible(msg.sender, true); } /** * @dev to get the verdict of kyc process * @param status is the kyc status * @param _add is the address of member */ function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); } /** * @dev transfering Ethers to newly created quotation contract. */ function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy { uint amount = address(this).balance; IERC20 erc20; if (amount > 0) { // newAdd.transfer(amount); Quotation newQT = Quotation(newAdd); newQT.sendEther.value(amount)(); } uint currAssetLen = pd.getAllCurrenciesLen(); for (uint64 i = 1; i < currAssetLen; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); address currAddr = pd.getCurrencyAssetAddress(currName); erc20 = IERC20(currAddr); //solhint-disable-line if (erc20.balanceOf(address(this)) > 0) { require(erc20.transfer(newAdd, erc20.balanceOf(address(this)))); } } } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover ( //solhint-disable-line address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod ) internal { uint cid = qd.getCoverLength(); qd.addCover(coverPeriod, coverDetails[0], from, coverCurr, scAddress, coverDetails[1], coverDetails[2]); // if cover period of quote is less than 60 days. if (coverPeriod <= 60) { p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days))); } uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100); tc.mint(from, coverNoteAmount); tf.lockCN(coverNoteAmount, coverPeriod, cid, from); qd.addInTotalSumAssured(coverCurr, coverDetails[0]); qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]); tf.pushStakerRewards(scAddress, coverDetails[2]); } /** * @dev Makes a vover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) internal { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s)); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause { address _add; bytes4 coverCurr; (, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid); qd.subFromTotalSumAssured(coverCurr, _amount); qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount); } /** * @dev to trigger the kyc process * @param status is the kyc status * @param _add is the address of member */ function _kycTrigger(bool status, address _add) internal { uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1); uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen); address payable userAdd; address scAddress; bytes4 coverCurr; uint16 coverPeriod; uint[] memory coverDetails = new uint[](4); IERC20 erc20; (, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID); (, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID); require(qd.refundEligible(userAdd)); qd.setRefundEligible(userAdd, false); require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending)); uint joinFee = td.joiningFee(); if (status) { mr.payJoiningFee.value(joinFee)(userAdd); if (coverDetails[3] > now) { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass)); address poolAdd = ms.getLatestAddress("P1"); if (coverCurr == "ETH") { p1.sendEther.value(coverDetails[1])(); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(poolAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed"); _makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod); } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover)); if (coverCurr == "ETH") { userAdd.transfer(coverDetails[1]); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed"); } } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); uint totalRefund = joinFee; if (coverCurr == "ETH") { totalRefund = coverDetails[1].add(joinFee); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } userAdd.transfer(totalRefund); emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed"); } } } // File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol pragma solidity 0.5.7; contract Factory { function getExchange(address token) public view returns (address); function getToken(address exchange) public view returns (address); } contract Exchange { function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256); function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256); function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256); function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient) public payable returns (uint256); function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline) public payable returns (uint256); function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient) public payable returns (uint256); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddress ) public returns (uint256); function tokenToTokenTransferInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address recipient, address tokenAddress ) public returns (uint256); } // File: nexusmutual-contracts/contracts/Pool2.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool2 is Iupgradable { using SafeMath for uint; MCR internal m1; Pool1 internal p1; PoolData internal pd; Factory internal factory; address public uniswapFactoryAddress; uint internal constant DECIMAL1E18 = uint(10) ** 18; bool internal locked; constructor(address _uniswapFactoryAdd) public { uniswapFactoryAddress = _uniswapFactoryAdd; factory = Factory(_uniswapFactoryAdd); } function() external payable {} event Liquidity(bytes16 typeOf, bytes16 functionName); event Rebalancing(bytes4 iaCurr, uint tokenAmount); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev to change the uniswap factory address * @param newFactoryAddress is the new factory address in concern * @return the status of the concerned coverId */ function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal { // require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender)); uniswapFactoryAddress = newFactoryAddress; factory = Factory(uniswapFactoryAddress); } /** * @dev On upgrade transfer all investment assets and ether to new Investment Pool * @param newPoolAddress New Investment Assest Pool address */ function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy { uint len = pd.getInvestmentCurrencyLen(); for (uint64 i = 1; i < len; i++) { bytes4 iaName = pd.getInvestmentCurrencyByIndex(i); _upgradeInvestmentPool(iaName, newPoolAddress); } if (address(this).balance > 0) { Pool2 newP2 = Pool2(newPoolAddress); newP2.sendEther.value(address(this).balance)(); } } /** * @dev Internal Swap of assets between Capital * and Investment Sub pool for excess or insufficient * liquidity conditions of a given currency. */ function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy { uint caBalance; uint baseMin; uint varMin; (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { _internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance); } else if (caBalance < uint(baseMin).add(varMin)) { _internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance); } } /** * @dev Saves a given investment asset details. To be called daily. * @param curr array of Investment asset name. * @param rate array of investment asset exchange rate. * @param date current date in yyyymmdd. */ function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit) external checkPause noReentrancy { bytes4 maxCurr; bytes4 minCurr; uint64 maxRate; uint64 minRate; //ONLY NOTARZIE ADDRESS CAN POST require(pd.isnotarise(msg.sender)); (maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate); pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date); pd.updatelastDate(date); uint len = curr.length; for (uint i = 0; i < len; i++) { pd.updateIAAvgRate(curr[i], rate[i]); } if (bit) //for testing purpose _rebalancingLiquidityTrading(maxCurr, maxRate); p1.saveIADetailsOracalise(pd.iaRatesTime()); } /** * @dev External Trade for excess or insufficient * liquidity conditions of a given currency. */ function externalLiquidityTrade() external onlyInternal { bool triggerTrade; bytes4 curr; bytes4 minIACurr; bytes4 maxIACurr; uint amount; uint minIARate; uint maxIARate; uint baseMin; uint varMin; uint caBalance; (maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate()); uint len = pd.getAllCurrenciesLen(); for (uint64 i = 0; i < len; i++) { curr = pd.getCurrenciesByIndex(i); (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18; triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount); } else if (caBalance < uint(baseMin).add(varMin)) { // insufficient amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance); triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount); } if (triggerTrade) { p1.triggerExternalLiquidityTrade(); } } } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); pd = PoolData(ms.getLatestAddress("PD")); p1 = Pool1(ms.getLatestAddress("P1")); } function sendEther() public payable { } /** * @dev Gets currency asset balance for a given currency name. */ function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) { if (_curr == "ETH") { caBalance = address(p1).balance; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); caBalance = erc20.balanceOf(address(p1)); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _transferInvestmentAsset( bytes4 _curr, address _transferTo, uint _amount ) internal { if (_curr == "ETH") { if (_amount > address(this).balance) _amount = address(this).balance; p1.sendEther.value(_amount)(); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (_amount > erc20.balanceOf(address(this))) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(_transferTo, _amount)); } } /** * @dev to perform rebalancing * @param iaCurr is the investment asset currency * @param iaRate is the investment asset rate */ function _rebalancingLiquidityTrading( bytes4 iaCurr, uint64 iaRate ) internal checkPause { uint amountToSell; uint totalRiskBal = pd.getLastVfull(); uint intermediaryEth; uint ethVol = pd.ethVolumeLimit(); totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18); Exchange exchange; if (totalRiskBal > 0) { amountToSell = ((totalRiskBal.mul(2).mul( iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000); amountToSell = (amountToSell.mul( 10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr))); intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000); } IERC20 erc20; erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr)); erc20.approve(address(exchange), amountToSell); exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice( amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { _transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell); } emit Rebalancing(iaCurr, amountToSell); } } /** * @dev Checks whether trading is required for a * given investment asset at a given exchange rate. */ function _checkTradeConditions( bytes4 curr, uint64 iaRate, uint totalRiskBal ) internal view returns(bool check) { if (iaRate > 0) { uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18); if (iaBalance > 0 && totalRiskBal > 0) { uint iaMax; uint iaMin; uint checkNumber; uint z; (iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr); z = pd.variationPercX100(); checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate)); if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) || (checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100))) check = true; //eligibleIA } } } /** * @dev Gets the investment asset rank. */ function _getIARank( bytes4 curr, uint64 rateX100, uint totalRiskPoolBalance ) internal view returns (int rhsh, int rhsl) //internal function { uint currentIAmaxHolding; uint currentIAminHolding; uint iaBalance = _getInvestmentAssetBalance(curr); (currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr); if (rateX100 > 0) { uint rhsf; rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100)); rhsh = int(rhsf - currentIAmaxHolding); rhsl = int(rhsf - currentIAminHolding); } } /** * @dev Calculates the investment asset rank. */ function _calculateIARank( bytes4[] memory curr, uint64[] memory rate ) internal view returns( bytes4 maxCurr, uint64 maxRate, bytes4 minCurr, uint64 minRate ) { int max = 0; int min = -1; int rhsh; int rhsl; uint totalRiskPoolBalance; (totalRiskPoolBalance, ) = m1.calVtpAndMCRtp(); uint len = curr.length; for (uint i = 0; i < len; i++) { rhsl = 0; rhsh = 0; if (pd.getInvestmentAssetStatus(curr[i])) { (rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance); if (rhsh > max || i == 0) { max = rhsh; maxCurr = curr[i]; maxRate = rate[i]; } if (rhsl < min || rhsl == 0 || i == 0) { min = rhsl; minCurr = curr[i]; minRate = rate[i]; } } } } /** * @dev to get balance of an investment asset * @param _curr is the investment asset in concern * @return the balance */ function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) { if (_curr == "ETH") { balance = address(this).balance; } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); balance = erc20.balanceOf(address(this)); } } /** * @dev Creates Excess liquidity trading order for a given currency and a given balance. */ function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { // require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender)); bytes4 minIACurr; // uint amount; (, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == minIACurr) { // amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18; p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2))); } else { p1.triggerExternalLiquidityTrade(); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. */ function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { bytes4 maxIACurr; uint amount; (maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == maxIACurr) { amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance); _transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); if ((maxIACurr == "ETH" && address(this).balance > 0) || (maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0)) p1.triggerExternalLiquidityTrade(); } } /** * @dev Creates External excess liquidity trading * order for a given currency and a given balance. * @param curr Currency Asset to Sell * @param minIACurr Investment Asset to Buy * @param amount Amount of Currency Asset to Sell */ function _externalExcessLiquiditySwap( bytes4 curr, bytes4 minIACurr, uint256 amount ) internal returns (bool trigger) { uint intermediaryEth; Exchange exchange; IERC20 erc20; uint ethVol = pd.ethVolumeLimit(); if (curr == minIACurr) { p1.transferCurrencyAsset(curr, amount); } else if (curr == "ETH" && minIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr))); if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit amount = (address(exchange).balance.mul(ethVol)).div(100); trigger = true; } p1.transferCurrencyAsset(curr, amount); exchange.ethToTokenSwapInput.value(amount) (exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now)); } else if (curr != "ETH" && minIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getTokenToEthInputPrice(amount); trigger = true; } p1.transferCurrencyAsset(curr, amount); // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } Exchange tmp = Exchange(factory.getExchange( pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) { intermediaryEth = address(tmp).balance.mul(ethVol).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } p1.transferCurrencyAsset(curr, amount); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); erc20.approve(address(exchange), amount); exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr)); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. * @param curr Currency Asset to buy * @param maxIACurr Investment Asset to sell * @param amount Amount of Investment Asset to sell */ function _externalInsufficientLiquiditySwap( bytes4 curr, bytes4 maxIACurr, uint256 amount ) internal returns (bool trigger) { Exchange exchange; IERC20 erc20; uint intermediaryEth; // uint ethVol = pd.ethVolumeLimit(); if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); intermediaryEth = exchange.getEthToTokenInputPrice(amount); if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getEthToTokenInputPrice(amount); trigger = true; } erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr)); if (intermediaryEth > erc20.balanceOf(address(this))) { intermediaryEth = erc20.balanceOf(address(this)); } // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), intermediaryEth); exchange.tokenToEthTransferInput(intermediaryEth, ( exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else if (curr != "ETH" && maxIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > address(this).balance) intermediaryEth = address(this).balance; if (intermediaryEth > (address(exchange).balance.mul (pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else { address currAdd = pd.getCurrencyAssetAddress(curr); exchange = Exchange(factory.getExchange(currAdd)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) { intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth); erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); uint maxIABal = erc20.balanceOf(address(this)); if (maxIAToSell > maxIABal) { maxIAToSell = maxIABal; intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); } amount = exchange.getEthToTokenInputPrice(intermediaryEth); erc20.approve(address(tmp), maxIAToSell); tmp.tokenToTokenTransferInput(maxIAToSell, ( amount.mul(995)).div(1000), ( intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _upgradeInvestmentPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } } // File: nexusmutual-contracts/contracts/Pool1.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool1 is usingOraclize, Iupgradable { using SafeMath for uint; Quotation internal q2; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; Pool2 internal p2; PoolData internal pd; MCR internal m1; Claims public c1; TokenData internal td; bool internal locked; uint internal constant DECIMAL1E18 = uint(10) ** 18; // uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18; event Apiresult(address indexed sender, string msg, bytes32 myid); event Payout(address indexed to, uint coverId, uint tokens); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } function () external payable {} //solhint-disable-line /** * @dev Pays out the sum assured in case a claim is accepted * @param coverid Cover Id. * @param claimid Claim Id. * @return succ true if payout is successful, false otherwise. */ function sendClaimPayout( uint coverid, uint claimid, uint sumAssured, address payable coverHolder, bytes4 coverCurr ) external onlyInternal noReentrancy returns(bool succ) { uint sa = sumAssured.div(DECIMAL1E18); bool check; IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //Payout if (coverCurr == "ETH" && address(this).balance >= sumAssured) { // check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured); coverHolder.transfer(sumAssured); check = true; } else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) { erc20.transfer(coverHolder, sumAssured); check = true; } if (check == true) { q2.removeSAFromCSA(coverid, sa); pd.changeCurrencyAssetVarMin(coverCurr, pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured)); emit Payout(coverHolder, coverid, sumAssured); succ = true; } else { c1.setClaimStatus(claimid, 12); } _triggerExternalLiquidityTrade(); // p2.internalLiquiditySwap(coverCurr); tf.burnStakerLockedToken(coverid, coverCurr, sumAssured); } /** * @dev to trigger external liquidity trade */ function triggerExternalLiquidityTrade() external onlyInternal { _triggerExternalLiquidityTrade(); } ///@dev Oraclize call to close emergency pause. function closeEmergencyPause(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000); _saveApiDetails(myid, "EP", 0); } /// @dev Calls the Oraclize Query to close a given Claim after a given period of time. /// @param id Claim Id to be closed /// @param time Time (in seconds) after which Claims assessment voting needs to be closed function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000); _saveApiDetails(myid, "CLA", id); } /// @dev Calls Oraclize Query to expire a given Cover after a given period of time. /// @param id Quote Id to be expired /// @param time Time (in seconds) after which the cover should be expired function closeCoverOraclise(uint id, uint64 time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat( "http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000); _saveApiDetails(myid, "COV", id); } /// @dev Calls the Oraclize Query to initiate MCR calculation. /// @param time Time (in milliseconds) after which the next MCR calculation should be initiated function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0); _saveApiDetails(myid, "MCR", 0); } /// @dev Calls the Oraclize Query in case MCR calculation fails. /// @param time Time (in seconds) after which the next MCR calculation should be initiated function mcrOracliseFail(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000); _saveApiDetails(myid, "MCRF", id); } /// @dev Oraclize call to update investment asset rates. function saveIADetailsOracalise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0); _saveApiDetails(myid, "IARB", 0); } /** * @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool * @param newPoolAddress Address of the new Pool */ function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal { for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 caName = pd.getCurrenciesByIndex(i); _upgradeCapitalPool(caName, newPoolAddress); } if (address(this).balance > 0) { Pool1 newP1 = Pool1(newPoolAddress); newP1.sendEther.value(address(this).balance)(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { m1 = MCR(ms.getLatestAddress("MC")); tk = NXMToken(ms.tokenAddress()); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); pd = PoolData(ms.getLatestAddress("PD")); q2 = Quotation(ms.getLatestAddress("QT")); p2 = Pool2(ms.getLatestAddress("P2")); c1 = Claims(ms.getLatestAddress("CL")); td = TokenData(ms.getLatestAddress("TD")); } function sendEther() public payable { } /** * @dev transfers currency asset to an address * @param curr is the currency of currency asset to transfer * @param amount is amount of currency asset to transfer * @return boolean to represent success or failure */ function transferCurrencyAsset( bytes4 curr, uint amount ) public onlyInternal noReentrancy returns(bool) { return _transferCurrencyAsset(curr, amount); } /// @dev Handles callback of external oracle query. function __callback(bytes32 myid, string memory result) public { result; //silence compiler warning // owner will be removed from production build ms.delegateCallBack(myid); } /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause payable { require(msg.value == coverDetails[1]); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed"); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /// @dev Enables user to purchase NXM at the current token price. function buyToken() public payable isMember checkPause returns(bool success) { require(msg.value > 0); uint tokenPurchased = _getToken(address(this).balance, msg.value); tc.mint(msg.sender, tokenPurchased); success = true; } /// @dev Sends a given amount of Ether to a given address. /// @param amount amount (in wei) to send. /// @param _add Receiver's address. /// @return succ True if transfer is a success, otherwise False. function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) { require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern"); succ = _add.send(amount); } /** * @dev Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) { require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance"); require(!tf.isLockedForMemberVote(msg.sender), "Member voted"); require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit"); uint sellingPrice = _getWei(_amount); tc.burnFrom(msg.sender, _amount); msg.sender.transfer(sellingPrice); success = true; } /** * @dev gives the investment asset balance * @return investment asset balance */ function getInvestmentAssetBalance() public view returns (uint balance) { IERC20 erc20; uint currTokens; for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) { bytes4 currency = pd.getInvestmentCurrencyByIndex(i); erc20 = IERC20(pd.getInvestmentAssetAddress(currency)); currTokens = erc20.balanceOf(address(p2)); if (pd.getIAAvgRate(currency) > 0) balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency))); } balance = balance.add(address(p2).balance); } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) public view returns(uint weiToPay) { return _getWei(amount); } /** * @dev Returns the amount of token a buyer will get for corresponding wei * @param weiPaid Amount of wei * @return tokenToGet Amount of tokens the buyer will get */ function getToken(uint weiPaid) public view returns(uint tokenToGet) { return _getToken((address(this).balance).add(weiPaid), weiPaid); } /** * @dev to trigger external liquidity trade */ function _triggerExternalLiquidityTrade() internal { if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) { pd.setLastLiquidityTradeTrigger(); bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000); _saveApiDetails(myid, "ULT", 0); } } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param _amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function _getWei(uint _amount) internal view returns(uint weiToPay) { uint tokenPrice; uint weiPaid; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calVtpAndMCRtp(); while (_amount > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5% if (_amount <= td.priceStep().mul(DECIMAL1E18)) { weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18)); break; } else { _amount = _amount.sub(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18)); weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18); vtp = vtp.sub(weiPaid); weiToPay = weiToPay.add(weiPaid); } } } /** * @dev gives the token * @param _poolBalance is the pool balance * @param _weiPaid is the amount paid in wei * @return the token to get */ function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) { uint tokenPrice; uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18); uint tempTokens; uint superWeiSpent; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid)); require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero"); while (superWeiLeft > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tempTokens = superWeiLeft.div(tokenPrice); if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) { tokenToGet = tokenToGet.add(tempTokens); break; } else { tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18)); superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice); superWeiLeft = superWeiLeft.sub(superWeiSpent); vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18)); } } } /** * @dev Save the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal, quote, cover etc. for which oraclize call is made. */ function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal { pd.saveApiDetails(myid, _typeof, id); pd.addInAllApiCall(myid); } /** * @dev transfers currency asset * @param _curr is currency of asset to transfer * @param _amount is the amount to be transferred * @return boolean representing the success of transfer */ function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) { if (_curr == "ETH") { if (address(this).balance < _amount) _amount = address(this).balance; p2.sendEther.value(_amount)(); succ = true; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line if (erc20.balanceOf(address(this)) < _amount) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(address(p2), _amount)); succ = true; } } /** * @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade. */ function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } /** * @dev oraclize query * @param paramCount is number of paramters passed * @param timestamp is the current timestamp * @param datasource in concern * @param arg in concern * @param gasLimit required for query * @return id of oraclize query */ function _oraclizeQuery( uint paramCount, uint timestamp, string memory datasource, string memory arg, uint gasLimit ) internal returns (bytes32 id) { if (paramCount == 4) { id = oraclize_query(timestamp, datasource, arg, gasLimit); } else if (paramCount == 3) { id = oraclize_query(timestamp, datasource, arg); } else { id = oraclize_query(datasource, arg); } } } // File: nexusmutual-contracts/contracts/MCR.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MCR is Iupgradable { using SafeMath for uint; Pool1 internal p1; PoolData internal pd; NXMToken internal tk; QuotationData internal qd; MemberRoles internal mr; TokenData internal td; ProposalCategory internal proposalCategory; uint private constant DECIMAL1E18 = uint(10) ** 18; uint private constant DECIMAL1E05 = uint(10) ** 5; uint private constant DECIMAL1E19 = uint(10) ** 19; uint private constant minCapFactor = uint(10) ** 21; uint public variableMincap; uint public dynamicMincapThresholdx100 = 13000; uint public dynamicMincapIncrementx100 = 100; event MCREvent( uint indexed date, uint blockNumber, bytes4[] allCurr, uint[] allCurrRates, uint mcrEtherx100, uint mcrPercx100, uint vFull ); /** * @dev Adds new MCR data. * @param mcrP Minimum Capital Requirement in percentage. * @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model. * @param onlyDate Date(yyyymmdd) at which MCR details are getting added. */ function addMCRData( uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate ) external checkPause { require(proposalCategory.constructorCheck()); require(pd.isnotarise(msg.sender)); if (mr.launched() && pd.capReached() != 1) { if (mcrP >= 10000) pd.setCapReached(1); } uint len = pd.getMCRDataLength(); _addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg); } /** * @dev Adds MCR Data for last failed attempt. */ function addLastMCRData(uint64 date) external checkPause onlyInternal { uint64 lastdate = uint64(pd.getLastMCRDate()); uint64 failedDate = uint64(date); if (failedDate >= lastdate) { uint mcrP; uint mcrE; uint vF; (mcrP, mcrE, vF, ) = pd.getLastMCR(); uint len = pd.getAllCurrenciesLen(); pd.pushMCRData(mcrP, mcrE, vF, date); for (uint j = 0; j < len; j++) { bytes4 currName = pd.getCurrenciesByIndex(j); pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName)); } emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF); // Oraclize call for next MCR calculation _callOracliseForMCR(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); tk = NXMToken(ms.tokenAddress()); mr = MemberRoles(ms.getLatestAddress("MR")); td = TokenData(ms.getLatestAddress("TD")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Gets total sum assured(in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns(uint amount) { uint len = pd.getAllCurrenciesLen(); for (uint i = 0; i < len; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); if (currName == "ETH") { amount = amount.add(qd.getTotalSumAssured(currName)); } else { if (pd.getCAAvgRate(currName) > 0) amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName))); } } } /** * @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether * and MCR% used in the Token Price Calculation. * @return vtp Pool Fund Value in Ether used for the Token Price Model * @return mcrtp MCR% used in the Token Price Model. */ function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { vtp = 0; IERC20 erc20; uint currTokens = 0; uint i; for (i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 currency = pd.getCurrenciesByIndex(i); erc20 = IERC20(pd.getCurrencyAssetAddress(currency)); currTokens = erc20.balanceOf(address(p1)); if (pd.getCAAvgRate(currency) > 0) vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency))); } vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance()); uint mcrFullperc; uint vFull; (mcrFullperc, , vFull, ) = pd.getLastMCR(); if (vFull > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); } } /** * @dev Calculates the Token Price of NXM in a given currency. * @param curr Currency name. */ function calculateStepTokenPrice( bytes4 curr, uint mcrtp ) public view onlyInternal returns(uint tokenPrice) { return _calculateTokenPrice(curr, mcrtp); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param curr Currency name. */ function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) { uint mcrtp; (, mcrtp) = _calVtpAndMCRtp(address(p1).balance); return _calculateTokenPrice(curr, mcrtp); } function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(address(p1).balance); } function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(poolBalance); } function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold) { minCap = (minCap.mul(minCapFactor)).add(variableMincap); uint lower = 0; if (vtp >= vF) { upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap } else { upperThreshold = vF.mul(120).mul(100).div((minCap)); } if (vtp > 0) { lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100); if(lower < minCap.mul(11).div(10)) lower = minCap.mul(11).div(10); } if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100 lowerThreshold = vtp.mul(100).mul(100).div(lower); } } /** * @dev Gets max numbers of tokens that can be sold at the moment. */ function getMaxSellTokens() public view returns(uint maxTokens) { uint baseMin = pd.getCurrencyAssetBaseMin("ETH"); uint maxTokensAccPoolBal; if (address(p1).balance > baseMin.mul(50).div(100)) { maxTokensAccPoolBal = address(p1).balance.sub( (baseMin.mul(50)).div(100)); } maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div( (calculateTokenPrice("ETH").mul(975)).div(1000)); uint lastMCRPerc = pd.getLastMCRPerc(); if (lastMCRPerc > 10000) maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000); if (maxTokens > maxTokensAccPoolBal) maxTokens = maxTokensAccPoolBal; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "DMCT") { val = dynamicMincapThresholdx100; } else if (code == "DMCI") { val = dynamicMincapIncrementx100; } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { dynamicMincapThresholdx100 = val; } else if (code == "DMCI") { dynamicMincapIncrementx100 = val; } else { revert("Invalid param code"); } } /** * @dev Calls oraclize query to calculate MCR details after 24 hours. */ function _callOracliseForMCR() internal { p1.mcrOraclise(pd.mcrTime()); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param _curr Currency name. * @return tokenPrice Token price. */ function _calculateTokenPrice( bytes4 _curr, uint mcrtp ) internal view returns(uint tokenPrice) { uint getA; uint getC; uint getCAAvgRate; uint tokenExponentValue = td.tokenExponent(); // uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp)); uint max = mcrtp ** tokenExponentValue; uint dividingFactor = tokenExponentValue.mul(4); (getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr); uint mcrEth = pd.getLastMCREther(); getC = getC.mul(DECIMAL1E18); tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor); tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05)); tokenPrice = tokenPrice.mul(getCAAvgRate * 10); tokenPrice = (tokenPrice).div(10**3); } /** * @dev Adds MCR Data. Checks if MCR is within valid * thresholds in order to rule out any incorrect calculations */ function _addMCRData( uint len, uint64 newMCRDate, bytes4[] memory curr, uint mcrE, uint mcrP, uint vF, uint[] memory _threeDayAvg ) internal { uint vtp = 0; uint lowerThreshold = 0; uint upperThreshold = 0; if (len > 1) { (vtp, ) = _calVtpAndMCRtp(address(p1).balance); (lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap()); } if(mcrP > dynamicMincapThresholdx100) variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000); // Explanation for above formula :- // actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100 // Implemented formula is simplified form of actual formula. // Let consider above formula as b = b + (a+b)*c/100 // here, dynamicMincapIncrement is in x100 format. // so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000. // It can further simplify to (b.(10000+cx100) + a.cx100)/10000. if (len == 1 || (mcrP) >= lowerThreshold && (mcrP) <= upperThreshold) { vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable pd.pushMCRData(mcrP, mcrE, vF, newMCRDate); for (uint i = 0; i < curr.length; i++) { pd.updateCAAvgRate(curr[i], _threeDayAvg[i]); } emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF); // Oraclize call for next MCR calculation if (vtp < newMCRDate) { _callOracliseForMCR(); } } else { p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime()); } } } // File: nexusmutual-contracts/contracts/Claims.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Claims is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; NXMToken internal tk; TokenController internal tc; ClaimsReward internal cr; Pool1 internal p1; ClaimsData internal cd; TokenData internal td; PoolData internal pd; Pool2 internal p2; QuotationData internal qd; MCR internal m1; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Gets claim details of claim id = pending claim start + given index */ function getClaimFromNewStart( uint index ) external view returns ( uint coverId, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { (coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender); // status = rewardStatus[statusnumber].claimStatusDesc; } /** * @dev Gets details of a claim submitted by the calling user, at a given index */ function getUserClaimByIndex( uint index ) external view returns( uint status, uint coverId, uint claimId ) { uint statusno; (statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender); status = statusno; } /** * @dev Gets details of a given claim id. * @param _claimId Claim Id. * @return status Current status of claim id * @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial * @return claimOwner Address through which claim is submitted * @return coverId Coverid associated with the claim id */ function getClaimbyIndex(uint _claimId) external view returns ( uint claimId, uint status, int8 finalVerdict, address claimOwner, uint coverId ) { uint stat; claimId = _claimId; (, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId); claimOwner = qd.getCoverMemberAddress(coverId); status = stat; } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns(uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function changePendingClaimStart() public onlyInternal { uint origstat; uint state12Count; uint pendingClaimStart = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = pendingClaimStart; i < actualClaimLength; i++) { (, , , origstat, , state12Count) = cd.getClaim(i); if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60))) cd.setpendingClaimStart(i); else break; } } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) public { address qadd = qd.getCoverMemberAddress(coverId); require(qadd == msg.sender); uint8 cStatus; (, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId); require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted"); require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired"); if (ms.isPause() == false) { _addClaim(coverId, now, qadd); } else { cd.setClaimAtEmergencyPause(coverId, now, false); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested)); } } /** * @dev Submits the Claims queued once the emergency pause is switched off. */ function submitClaimAfterEPOff() public onlyInternal { uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP(); uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP(); uint coverId; uint dateUpd; bool submit; address qadd; for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) { (coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i); require(submit == false); qadd = qd.getCoverMemberAddress(coverId); _addClaim(coverId, dateUpd, qadd); cd.setClaimSubmittedAtEPTrue(i, true); } cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP); } /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Pause Voting of All Pending Claims when Emergency Pause Start. */ function pauseAllPendingClaimsVoting() public onlyInternal { uint firstIndex = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = firstIndex; i < actualClaimLength; i++) { if (checkVoteClosing(i) == 0) { uint dateUpd = cd.getClaimDateUpd(i); cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false); } } } /** * @dev Resume the voting phase of all Claims paused due to an emergency pause. */ function startAllPendingClaimsVoting() public onlyInternal { uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP(); uint i; uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause(); for (i = firstIndx; i < lengthOfClaimVotingPause; i++) { uint pendingTime; uint claimID; (claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i); uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime); cd.setClaimdateUpd(claimID, pTime); cd.setPendingClaimVoteStatus(i, true); uint coverid; (, coverid) = cd.getClaimCoverId(claimID); address qadd = qd.getCoverMemberAddress(coverid); tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime())); p1.closeClaimsOraclise(claimID, uint64(pTime)); } cd.setFirstClaimIndexToStartVotingAfterEP(i); } /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns(int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = -1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } uint time = now; cd.setClaimdateUpd(claimId, time); if (stat >= 2 && stat <= 5) { p1.closeClaimsOraclise(claimId, cd.maxVotingTime()); } if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) { p1.closeClaimsOraclise(claimId, cd.payoutRetryTime()); } else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) { uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now)); p1.closeClaimsOraclise(claimId, timeLeft); } } /** * @dev Submits a claim for a given cover note. * Set deposits flag against cover. */ function _addClaim(uint coverId, uint time, address add) internal { tf.depositCN(coverId); uint len = cd.actualClaimLength(); cd.addClaim(len, coverId, add, now); cd.callClaimEvent(coverId, add, len, time); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); bytes4 curr = qd.getCurrencyOfCover(coverId); uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured)); p2.internalLiquiditySwap(curr); p1.closeClaimsOraclise(len, cd.maxVotingTime()); } } // File: nexusmutual-contracts/contracts/ClaimsReward.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity 0.5.7; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool1 internal p1; Pool2 internal p2; PoolData internal pd; Governance internal gv; IPooledStaking internal pooledStaking; uint private constant DECIMAL1E18 = uint(10) ** 18; function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { uint coverid; (, coverid) = cd.getClaimCoverId(claimid); uint status; (, status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) { // when current status is "Claim Accepted Payout Pending" uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); address payable coverHolder = qd.getCoverMemberAddress(coverid); bytes4 coverCurrency = qd.getCurrencyOfCover(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency); if (success) { tf.burnStakedTokens(coverid, coverCurrency, sumAssured); c1.setClaimStatus(claimid, 14); } } c1.changePendingClaimStart(); } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenCA(claimId); } else { (, , totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenMV(claimId); }else { (, , totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns(uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } (reward, , , ) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns(uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); bytes4 curr = qd.getCurrencyOfCover(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); td.setDepositCN(coverid, false); // Unset flag tf.burnDepositCN(coverid); // burn Deposited CN pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured)); p2.internalLiquiditySwap(curr); } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); td.setDepositCN(coverid, false); // Unset flag tf.unlockCN(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr); if (success) { tf.burnStakedTokens(coverid, curr, sumAssured); } } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, -1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, -1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex, ) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc, , ) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total=0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); //solhint-disable-line } } // File: nexusmutual-contracts/contracts/MemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MemberRoles is IMemberRoles, Governed, Iupgradable { TokenController public dAppToken; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember ( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner ( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); dAppToken = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate (address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole( //solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole( //solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i=0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); dAppToken.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); dAppToken.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); //solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); //solhint-disable-line } } /** * @dev Called by existed member if wish to Withdraw membership. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist } /** * @dev Called by existed member if wish to switch membership to other address. * @param _add address of user to forward membership. */ function switchMembership(address _add) external { require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.addToWhitelist(_add); _updateRole(_add, uint(Role.Member), true); tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); emit switchedMembership(msg.sender, _add, now); } /// @dev Return number of member roles function totalRoles() public view returns(uint256) { //solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns(bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } // File: nexusmutual-contracts/contracts/ProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping (uint => CategoryAction) internal categoryActionData; mapping (uint => uint) public categoryABReq; mapping (uint => uint) public isSpecialResolution; mapping (uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Restricts calls to deprecated functions */ modifier deprecated() { revert("Function deprecated"); _; } /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external deprecated { } /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external deprecated { //solhint-disable-line } /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns(uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) { return( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) { return( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public deprecated { } /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns(uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Initiates add solution /// @param _solutionHash Solution hash having required data against adding solution function addSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Opens proposal for voting function openProposalForVoting(uint _proposalId) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function pauseProposal(uint _proposalId) public; function resumeProposal(uint _proposalId) public; function allowedToCatgorize() public view returns(uint roleId); } // File: nexusmutual-contracts/contracts/Governance.sol // /* Copyright (C) 2017 GovBlocks.io // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint=>uint) memberVoteValue; mapping(uint=>uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping (address => mapping(uint => uint)) public memberProposalVote; mapping (address => uint) public followerDelegation; mapping (address => uint) internal followerCount; mapping (address => uint[]) internal leaderDelegation; mapping (uint => VoteTally) public proposalVoteTally; mapping (address => bool) public isOpenForDelegation; mapping (address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Initiates add solution * To implement the governance interface */ function addSolution(uint, string calldata, bytes calldata) external { } /** * @dev Opens proposal for voting * To implement the governance interface */ function openProposalForVoting(uint) external { } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) { return( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns(uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns(uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns(bool check) { if (category == 0) return true; uint[] memory mrAllowed; (, , , , mrAllowed, , ) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns(bool delegated) { for (uint i=0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Pauses a proposal * To implement govblocks interface */ function pauseProposal(uint) public { } /** * @dev Resumes a proposal * To implement govblocks interface */ function resumeProposal(uint) public { } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns(uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns(uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime, ) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10**18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10**18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns(uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns(bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } (bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (, , majorityVote, , , , ) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (, , _majorityVote, , , , ) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } }
Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal { stlp = _stlp; }
7,286,923
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; interface IPoolFactory { function isPool(address pool) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev 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.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.10; import {Address} from "Address.sol"; import {Context} from "Context.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {Initializable} from "Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, 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. */ function __ERC20_initialize(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public virtual view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ITrueLender2 { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); // @dev distribute a basket of tokens for exiting user function distribute( address recipient, uint256 numerator, uint256 denominator ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IERC20WithDecimals is IERC20 { function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20WithDecimals} from "IERC20WithDecimals.sol"; /** * @dev Oracle that converts any token to and from TRU * Used for liquidations and valuing of liquidated TRU in the pool */ interface ITrueFiPoolOracle { // token address function token() external view returns (IERC20WithDecimals); // amount of tokens 1 TRU is worth function truToToken(uint256 truAmount) external view returns (uint256); // amount of TRU 1 token is worth function tokenToTru(uint256 tokenAmount) external view returns (uint256); // USD price of token with 18 decimals function tokenToUsd(uint256 tokenAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface I1Inch3 { struct SwapDescription { address srcToken; address dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; } function swap( address caller, SwapDescription calldata desc, bytes calldata data ) external returns ( uint256 returnAmount, uint256 gasLeft, uint256 chiSpent ); function unoswap( address srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) external payable returns (uint256 returnAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20, IERC20} from "UpgradeableERC20.sol"; import {ITrueLender2} from "ITrueLender2.sol"; import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol"; import {I1Inch3} from "I1Inch3.sol"; interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, ERC20 _stakingToken, ITrueLender2 _lender, I1Inch3 __1Inch, address __owner ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); /** * @dev Join the pool by depositing tokens * @param amount amount of tokens to deposit */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount) external; /** * @dev pay borrowed money back to pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 currencyAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanFactory2 { function createLoanToken( ITrueFiPool2 _pool, uint256 _amount, uint256 _term, uint256 _apy ) external; function isLoanToken(address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "Context.sol"; import "IERC20.sol"; import "SafeMath.sol"; import "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 "SafeMath.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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.10; import {IERC20} from "IERC20.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanToken2 is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function profit() external view returns (uint256); function status() external view returns (Status); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function token() external view returns (IERC20); function version() external pure returns (uint8); } //interface IContractWithPool { // function pool() external view returns (ITrueFiPool2); //} // //// Had to be split because of multiple inheritance problem //interface ILoanToken2 is ILoanToken, IContractWithPool { // //} // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface ILoanToken is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function profit() external view returns (uint256); function status() external view returns (Status); function borrowerFee() external view returns (uint256); function receivedAmount() external view returns (uint256); function isLoanToken() external pure returns (bool); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function currencyToken() external view returns (IERC20); function version() external pure returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20} from "ERC20.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ILoanToken} from "ILoanToken.sol"; /** * @title LoanToken * @dev A token which represents share of a debt obligation * * Each LoanToken has: * - borrower address * - borrow amount * - loan term * - loan APY * * Loan progresses through the following states: * Awaiting: Waiting for funding to meet capital requirements * Funded: Capital requirements met, borrower can withdraw * Withdrawn: Borrower withdraws money, loan waiting to be repaid * Settled: Loan has been paid back in full with interest * Defaulted: Loan has not been paid back in full * Liquidated: Loan has Defaulted and stakers have been Liquidated * * - LoanTokens are non-transferable except for whitelisted addresses * - This version of LoanToken only supports a single funder */ contract LoanToken is ILoanToken, ERC20 { using SafeMath for uint256; using SafeERC20 for IERC20; uint128 public constant lastMinutePaybackDuration = 1 days; address public override borrower; address public liquidator; uint256 public override amount; uint256 public override term; uint256 public override apy; uint256 public override start; address public override lender; uint256 public override debt; uint256 public redeemed; // borrow fee -> 25 = 0.25% uint256 public override borrowerFee = 25; // whitelist for transfers mapping(address => bool) public canTransfer; Status public override status; IERC20 public override currencyToken; /** * @dev Emitted when the loan is funded * @param lender Address which funded the loan */ event Funded(address lender); /** * @dev Emitted when transfer whitelist is updated * @param account Account to whitelist for transfers * @param status New whitelist status */ event TransferAllowanceChanged(address account, bool status); /** * @dev Emitted when borrower withdraws funds * @param beneficiary Account which will receive funds */ event Withdrawn(address beneficiary); /** * @dev Emitted when loan has been fully repaid * @param returnedAmount Amount that was returned */ event Settled(uint256 returnedAmount); /** * @dev Emitted when term is over without full repayment * @param returnedAmount Amount that was returned before expiry */ event Defaulted(uint256 returnedAmount); /** * @dev Emitted when a LoanToken is redeemed for underlying currencyTokens * @param receiver Receiver of currencyTokens * @param burnedAmount Amount of LoanTokens burned * @param redeemedAmount Amount of currencyToken received */ event Redeemed(address receiver, uint256 burnedAmount, uint256 redeemedAmount); /** * @dev Emitted when a LoanToken is repaid by the borrower in underlying currencyTokens * @param repayer Sender of currencyTokens * @param repaidAmount Amount of currencyToken repaid */ event Repaid(address repayer, uint256 repaidAmount); /** * @dev Emitted when borrower reclaims remaining currencyTokens * @param borrower Receiver of remaining currencyTokens * @param reclaimedAmount Amount of currencyTokens repaid */ event Reclaimed(address borrower, uint256 reclaimedAmount); /** * @dev Emitted when loan gets liquidated * @param status Final loan status */ event Liquidated(Status status); /** * @dev Create a Loan * @param _currencyToken Token to lend * @param _borrower Borrower address * @param _amount Borrow amount of currency tokens * @param _term Loan length * @param _apy Loan APY */ constructor( IERC20 _currencyToken, address _borrower, address _lender, address _liquidator, uint256 _amount, uint256 _term, uint256 _apy ) public ERC20("Loan Token", "LOAN") { require(_lender != address(0), "LoanToken: Lender is not set"); currencyToken = _currencyToken; borrower = _borrower; liquidator = _liquidator; amount = _amount; term = _term; apy = _apy; lender = _lender; debt = interest(amount); } /** * @dev Only borrower can withdraw & repay loan */ modifier onlyBorrower() { require(msg.sender == borrower, "LoanToken: Caller is not the borrower"); _; } /** * @dev Only liquidator can liquidate */ modifier onlyLiquidator() { require(msg.sender == liquidator, "LoanToken: Caller is not the liquidator"); _; } /** * @dev Only after loan has been closed: Settled, Defaulted, or Liquidated */ modifier onlyAfterClose() { require(status >= Status.Settled, "LoanToken: Only after loan has been closed"); _; } /** * @dev Only when loan is Funded */ modifier onlyOngoing() { require(status == Status.Funded || status == Status.Withdrawn, "LoanToken: Current status should be Funded or Withdrawn"); _; } /** * @dev Only when loan is Funded */ modifier onlyFunded() { require(status == Status.Funded, "LoanToken: Current status should be Funded"); _; } /** * @dev Only when loan is Withdrawn */ modifier onlyAfterWithdraw() { require(status >= Status.Withdrawn, "LoanToken: Only after loan has been withdrawn"); _; } /** * @dev Only when loan is Awaiting */ modifier onlyAwaiting() { require(status == Status.Awaiting, "LoanToken: Current status should be Awaiting"); _; } /** * @dev Only when loan is Defaulted */ modifier onlyDefaulted() { require(status == Status.Defaulted, "LoanToken: Current status should be Defaulted"); _; } /** * @dev Only whitelisted accounts or lender */ modifier onlyWhoCanTransfer(address sender) { require( sender == lender || canTransfer[sender], "LoanToken: This can be performed only by lender or accounts allowed to transfer" ); _; } /** * @dev Only lender can perform certain actions */ modifier onlyLender() { require(msg.sender == lender, "LoanToken: This can be performed only by lender"); _; } /** * @dev Return true if this contract is a LoanToken * @return True if this contract is a LoanToken */ function isLoanToken() external override pure returns (bool) { return true; } /** * @dev Get loan parameters * @return amount, term, apy */ function getParameters() external override view returns ( uint256, uint256, uint256 ) { return (amount, apy, term); } /** * @dev Get coupon value of this loan token in currencyToken * This assumes the loan will be paid back on time, with interest * @param _balance number of LoanTokens to get value for * @return coupon value of _balance LoanTokens in currencyTokens */ function value(uint256 _balance) external override view returns (uint256) { if (_balance == 0) { return 0; } uint256 passed = block.timestamp.sub(start); if (passed > term || status == Status.Settled) { passed = term; } // assume year is 365 days uint256 interest = amount.mul(apy).mul(passed).div(365 days).div(10000); return amount.add(interest).mul(_balance).div(debt); } /** * @dev Fund a loan * Set status, start time, lender */ function fund() external override onlyAwaiting onlyLender { status = Status.Funded; start = block.timestamp; _mint(msg.sender, debt); currencyToken.safeTransferFrom(msg.sender, address(this), receivedAmount()); emit Funded(msg.sender); } /** * @dev Whitelist accounts to transfer * @param account address to allow transfers for * @param _status true allows transfers, false disables transfers */ function allowTransfer(address account, bool _status) external override onlyLender { canTransfer[account] = _status; emit TransferAllowanceChanged(account, _status); } /** * @dev Borrower calls this function to withdraw funds * Sets the status of the loan to Withdrawn * @param _beneficiary address to send funds to */ function withdraw(address _beneficiary) external override onlyBorrower onlyFunded { status = Status.Withdrawn; currencyToken.safeTransfer(_beneficiary, receivedAmount()); emit Withdrawn(_beneficiary); } /** * @dev Settle the loan after checking it has been repaid */ function settle() public override onlyOngoing { require(isRepaid(), "LoanToken: loan must be repaid to settle"); status = Status.Settled; emit Settled(_balance()); } /** * @dev Default the loan if it has not been repaid by the end of term */ function enterDefault() external override onlyOngoing { require(!isRepaid(), "LoanToken: cannot default a repaid loan"); require(start.add(term).add(lastMinutePaybackDuration) <= block.timestamp, "LoanToken: Loan cannot be defaulted yet"); status = Status.Defaulted; emit Defaulted(_balance()); } /** * @dev Liquidate the loan if it has defaulted */ function liquidate() external override onlyDefaulted onlyLiquidator { status = Status.Liquidated; emit Liquidated(status); } /** * @dev Redeem LoanToken balances for underlying currencyToken * Can only call this function after the loan is Closed * @param _amount amount to redeem */ function redeem(uint256 _amount) external override onlyAfterClose { uint256 amountToReturn = _amount.mul(_balance()).div(totalSupply()); redeemed = redeemed.add(amountToReturn); _burn(msg.sender, _amount); currencyToken.safeTransfer(msg.sender, amountToReturn); emit Redeemed(msg.sender, _amount, amountToReturn); } /** * @dev Function for borrower to repay the loan * Borrower can repay at any time * @param _sender account sending currencyToken to repay * @param _amount amount of currencyToken to repay */ function repay(address _sender, uint256 _amount) external override { _repay(_sender, _amount); } /** * @dev Function for borrower to repay all of the remaining loan balance * Borrower should use this to ensure full repayment * @param _sender account sending currencyToken to repay */ function repayInFull(address _sender) external override { _repay(_sender, debt.sub(_balance())); } /** * @dev Internal function for loan repayment * If _amount is sufficient, then this also settles the loan * @param _sender account sending currencyToken to repay * @param _amount amount of currencyToken to repay */ function _repay(address _sender, uint256 _amount) internal onlyAfterWithdraw { require(_amount <= debt.sub(_balance()), "LoanToken: Cannot repay over the debt"); emit Repaid(_sender, _amount); currencyToken.safeTransferFrom(_sender, address(this), _amount); if (isRepaid()) { settle(); } } /** * @dev Function for borrower to reclaim stuck currencyToken * Can only call this function after the loan is Closed * and all of LoanToken holders have been burnt */ function reclaim() external override onlyAfterClose onlyBorrower { require(totalSupply() == 0, "LoanToken: Cannot reclaim when LoanTokens are in circulation"); uint256 balanceRemaining = _balance(); require(balanceRemaining > 0, "LoanToken: Cannot reclaim when balance 0"); currencyToken.safeTransfer(borrower, balanceRemaining); emit Reclaimed(borrower, balanceRemaining); } /** * @dev Check how much was already repaid * Funds stored on the contract's address plus funds already redeemed by lenders * @return Uint256 representing what value was already repaid */ function repaid() external override view onlyAfterWithdraw returns (uint256) { return _balance().add(redeemed); } /** * @dev Check whether an ongoing loan has been repaid in full * @return true if and only if this loan has been repaid */ function isRepaid() public override view onlyOngoing returns (bool) { return _balance() >= debt; } /** * @dev Public currency token balance function * @return currencyToken balance of this contract */ function balance() external override view returns (uint256) { return _balance(); } /** * @dev Get currency token balance for this contract * @return currencyToken balance of this contract */ function _balance() internal view returns (uint256) { return currencyToken.balanceOf(address(this)); } /** * @dev Calculate amount borrowed minus fee * @return Amount minus fees */ function receivedAmount() public override view returns (uint256) { return amount.sub(amount.mul(borrowerFee).div(10000)); } /** * @dev Calculate interest that will be paid by this loan for an amount (returned funds included) * amount + ((amount * apy * term) / (365 days / precision)) * @param _amount amount * @return uint256 Amount of interest paid for _amount */ function interest(uint256 _amount) internal view returns (uint256) { return _amount.add(_amount.mul(apy).mul(term).div(365 days).div(10000)); } /** * @dev get profit for this loan * @return profit for this loan */ function profit() external override view returns (uint256) { return debt.sub(amount); } /** * @dev Override ERC20 _transfer so only whitelisted addresses can transfer * @param sender sender of the transaction * @param recipient recipient of the transaction * @param _amount amount to send */ function _transfer( address sender, address recipient, uint256 _amount ) internal override onlyWhoCanTransfer(sender) { return super._transfer(sender, recipient, _amount); } function version() external virtual override pure returns (uint8) { return 3; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20} from "ERC20.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ILoanToken2, ITrueFiPool2} from "ILoanToken2.sol"; import {LoanToken} from "LoanToken.sol"; /** * @title LoanToken V2 * @dev A token which represents share of a debt obligation * * Each LoanToken has: * - borrower address * - borrow amount * - loan term * - loan APY * * Loan progresses through the following states: * Awaiting: Waiting for funding to meet capital requirements * Funded: Capital requirements met, borrower can withdraw * Withdrawn: Borrower withdraws money, loan waiting to be repaid * Settled: Loan has been paid back in full with interest * Defaulted: Loan has not been paid back in full * Liquidated: Loan has Defaulted and stakers have been Liquidated * * - LoanTokens are non-transferable except for whitelisted addresses * - This version of LoanToken only supports a single funder */ contract LoanToken2 is ILoanToken2, ERC20 { using SafeMath for uint256; using SafeERC20 for IERC20; uint128 public constant LAST_MINUTE_PAYBACK_DURATION = 1 days; uint256 private constant APY_PRECISION = 10000; address public override borrower; address public liquidator; uint256 public override amount; uint256 public override term; // apy precision: 10000 = 100% uint256 public override apy; uint256 public override start; address public override lender; uint256 public override debt; uint256 public redeemed; // whitelist for transfers mapping(address => bool) public canTransfer; Status public override status; IERC20 public override token; ITrueFiPool2 public override pool; /** * @dev Emitted when the loan is funded * @param lender Address which funded the loan */ event Funded(address lender); /** * @dev Emitted when transfer whitelist is updated * @param account Account to whitelist for transfers * @param status New whitelist status */ event TransferAllowanceChanged(address account, bool status); /** * @dev Emitted when borrower withdraws funds * @param beneficiary Account which will receive funds */ event Withdrawn(address beneficiary); /** * @dev Emitted when loan has been fully repaid * @param returnedAmount Amount that was returned */ event Settled(uint256 returnedAmount); /** * @dev Emitted when term is over without full repayment * @param returnedAmount Amount that was returned before expiry */ event Defaulted(uint256 returnedAmount); /** * @dev Emitted when a LoanToken is redeemed for underlying tokens * @param receiver Receiver of tokens * @param burnedAmount Amount of LoanTokens burned * @param redeemedAmount Amount of token received */ event Redeemed(address receiver, uint256 burnedAmount, uint256 redeemedAmount); /** * @dev Emitted when a LoanToken is repaid by the borrower in underlying tokens * @param repayer Sender of tokens * @param repaidAmount Amount of token repaid */ event Repaid(address repayer, uint256 repaidAmount); /** * @dev Emitted when borrower reclaims remaining tokens * @param borrower Receiver of remaining tokens * @param reclaimedAmount Amount of tokens repaid */ event Reclaimed(address borrower, uint256 reclaimedAmount); /** * @dev Emitted when loan gets liquidated * @param status Final loan status */ event Liquidated(Status status); /** * @dev Create a Loan * @param _pool Pool to lend from * @param _borrower Borrower address * @param _lender Lender address * @param _liquidator Liquidator address * @param _amount Borrow amount of loaned tokens * @param _term Loan length * @param _apy Loan APY */ constructor( ITrueFiPool2 _pool, address _borrower, address _lender, address _liquidator, uint256 _amount, uint256 _term, uint256 _apy ) public ERC20("TrueFi Loan Token", "LOAN") { require(_lender != address(0), "LoanToken2: Lender is not set"); pool = _pool; token = _pool.token(); borrower = _borrower; liquidator = _liquidator; amount = _amount; term = _term; apy = _apy; lender = _lender; debt = interest(amount); } /** * @dev Only borrower can withdraw & repay loan */ modifier onlyBorrower() { require(msg.sender == borrower, "LoanToken2: Caller is not the borrower"); _; } /** * @dev Only liquidator can liquidate */ modifier onlyLiquidator() { require(msg.sender == liquidator, "LoanToken2: Caller is not the liquidator"); _; } /** * @dev Only after loan has been closed: Settled, Defaulted, or Liquidated */ modifier onlyAfterClose() { require(status >= Status.Settled, "LoanToken2: Only after loan has been closed"); _; } /** * @dev Only when loan is Funded */ modifier onlyOngoing() { require(status == Status.Funded || status == Status.Withdrawn, "LoanToken2: Current status should be Funded or Withdrawn"); _; } /** * @dev Only when loan is Funded */ modifier onlyFunded() { require(status == Status.Funded, "LoanToken2: Current status should be Funded"); _; } /** * @dev Only when loan is Withdrawn */ modifier onlyAfterWithdraw() { require(status >= Status.Withdrawn, "LoanToken2: Only after loan has been withdrawn"); _; } /** * @dev Only when loan is Awaiting */ modifier onlyAwaiting() { require(status == Status.Awaiting, "LoanToken2: Current status should be Awaiting"); _; } /** * @dev Only when loan is Defaulted */ modifier onlyDefaulted() { require(status == Status.Defaulted, "LoanToken2: Current status should be Defaulted"); _; } /** * @dev Only whitelisted accounts or lender */ modifier onlyWhoCanTransfer(address sender) { require( sender == lender || canTransfer[sender], "LoanToken2: This can be performed only by lender or accounts allowed to transfer" ); _; } /** * @dev Only lender can perform certain actions */ modifier onlyLender() { require(msg.sender == lender, "LoanToken2: This can be performed only by lender"); _; } /** * @dev Get loan parameters * @return amount, term, apy */ function getParameters() external override view returns ( uint256, uint256, uint256 ) { return (amount, apy, term); } /** * @dev Get coupon value of this loan token in token * This assumes the loan will be paid back on time, with interest * @param _balance number of LoanTokens to get value for * @return coupon value of _balance LoanTokens in tokens */ function value(uint256 _balance) external override view returns (uint256) { if (_balance == 0) { return 0; } uint256 passed = block.timestamp.sub(start); if (passed > term || status == Status.Settled) { passed = term; } // assume year is 365 days uint256 interest = amount.mul(apy).mul(passed).div(365 days).div(APY_PRECISION); return amount.add(interest).mul(_balance).div(debt); } /** * @dev Fund a loan * Set status, start time, lender */ function fund() external override onlyAwaiting onlyLender { status = Status.Funded; start = block.timestamp; _mint(msg.sender, debt); token.safeTransferFrom(msg.sender, address(this), amount); emit Funded(msg.sender); } /** * @dev Whitelist accounts to transfer * @param account address to allow transfers for * @param _status true allows transfers, false disables transfers */ function allowTransfer(address account, bool _status) external override onlyLender { canTransfer[account] = _status; emit TransferAllowanceChanged(account, _status); } /** * @dev Borrower calls this function to withdraw funds * Sets the status of the loan to Withdrawn * @param _beneficiary address to send funds to */ function withdraw(address _beneficiary) external override onlyBorrower onlyFunded { status = Status.Withdrawn; token.safeTransfer(_beneficiary, amount); emit Withdrawn(_beneficiary); } /** * @dev Settle the loan after checking it has been repaid */ function settle() public override onlyOngoing { require(isRepaid(), "LoanToken2: loan must be repaid to settle"); status = Status.Settled; emit Settled(_balance()); } /** * @dev Default the loan if it has not been repaid by the end of term */ function enterDefault() external override onlyOngoing { require(!isRepaid(), "LoanToken2: cannot default a repaid loan"); require(start.add(term).add(LAST_MINUTE_PAYBACK_DURATION) <= block.timestamp, "LoanToken2: Loan cannot be defaulted yet"); status = Status.Defaulted; emit Defaulted(_balance()); } /** * @dev Liquidate the loan if it has defaulted */ function liquidate() external override onlyDefaulted onlyLiquidator { status = Status.Liquidated; emit Liquidated(status); } /** * @dev Redeem LoanToken balances for underlying token * Can only call this function after the loan is Closed * @param _amount amount to redeem */ function redeem(uint256 _amount) external override onlyAfterClose { uint256 amountToReturn = _amount.mul(_balance()).div(totalSupply()); redeemed = redeemed.add(amountToReturn); _burn(msg.sender, _amount); token.safeTransfer(msg.sender, amountToReturn); emit Redeemed(msg.sender, _amount, amountToReturn); } /** * @dev Function for borrower to repay the loan * Borrower can repay at any time * @param _sender account sending token to repay * @param _amount amount of token to repay */ function repay(address _sender, uint256 _amount) external override { _repay(_sender, _amount); } /** * @dev Function for borrower to repay all of the remaining loan balance * Borrower should use this to ensure full repayment * @param _sender account sending token to repay */ function repayInFull(address _sender) external override { _repay(_sender, debt.sub(_balance())); } /** * @dev Internal function for loan repayment * If _amount is sufficient, then this also settles the loan * @param _sender account sending token to repay * @param _amount amount of token to repay */ function _repay(address _sender, uint256 _amount) internal onlyAfterWithdraw { require(_amount <= debt.sub(_balance()), "LoanToken2: Cannot repay over the debt"); emit Repaid(_sender, _amount); token.safeTransferFrom(_sender, address(this), _amount); if (isRepaid()) { settle(); } } /** * @dev Function for borrower to reclaim stuck token * Can only call this function after the loan is Closed * and all of LoanToken holders have been burnt */ function reclaim() external override onlyAfterClose onlyBorrower { require(totalSupply() == 0, "LoanToken2: Cannot reclaim when LoanTokens are in circulation"); uint256 balanceRemaining = _balance(); require(balanceRemaining > 0, "LoanToken2: Cannot reclaim when balance 0"); token.safeTransfer(borrower, balanceRemaining); emit Reclaimed(borrower, balanceRemaining); } /** * @dev Check how much was already repaid * Funds stored on the contract's address plus funds already redeemed by lenders * @return Uint256 representing what value was already repaid */ function repaid() external override view onlyAfterWithdraw returns (uint256) { return _balance().add(redeemed); } /** * @dev Check whether an ongoing loan has been repaid in full * @return true if and only if this loan has been repaid */ function isRepaid() public override view onlyOngoing returns (bool) { return _balance() >= debt; } /** * @dev Public currency token balance function * @return token balance of this contract */ function balance() external override view returns (uint256) { return _balance(); } /** * @dev Get currency token balance for this contract * @return token balance of this contract */ function _balance() internal view returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Calculate interest that will be paid by this loan for an amount (returned funds included) * amount + ((amount * apy * term) / 365 days / precision) * @param _amount amount * @return uint256 Amount of interest paid for _amount */ function interest(uint256 _amount) internal view returns (uint256) { return _amount.add(_amount.mul(apy).mul(term).div(365 days).div(APY_PRECISION)); } /** * @dev get profit for this loan * @return profit for this loan */ function profit() external override view returns (uint256) { return debt.sub(amount); } /** * @dev Override ERC20 _transfer so only whitelisted addresses can transfer * @param sender sender of the transaction * @param recipient recipient of the transaction * @param _amount amount to send */ function _transfer( address sender, address recipient, uint256 _amount ) internal override onlyWhoCanTransfer(sender) { return super._transfer(sender, recipient, _amount); } function version() external override pure returns (uint8) { return 4; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Initializable} from "Initializable.sol"; import {IPoolFactory} from "IPoolFactory.sol"; import {ILoanFactory2} from "ILoanFactory2.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {LoanToken2, IERC20} from "LoanToken2.sol"; /** * @title LoanFactory2 * @notice Deploy LoanTokens for pools created by PoolFactory, with this Contract * @dev LoanTokens are deployed through a factory to ensure that all * LoanTokens adhere to the same contract code, rather than using an interface. */ contract LoanFactory2 is ILoanFactory2, Initializable { // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== // @dev Track Valid LoanTokens mapping(address => bool) public override isLoanToken; IPoolFactory public poolFactory; address public lender; address public liquidator; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted when a LoanToken is created * @param contractAddress LoanToken contract address */ event LoanTokenCreated(address contractAddress); /** * @dev Initialize this contract and set currency token * @param _poolFactory PoolFactory address * @param _lender Lender address * @param _liquidator Liquidator address */ function initialize( IPoolFactory _poolFactory, address _lender, address _liquidator ) external initializer { poolFactory = _poolFactory; lender = _lender; liquidator = _liquidator; } /** * @dev Deploy LoanToken with parameters * @param _amount Amount to borrow * @param _term Length of loan * @param _apy Loan yield */ function createLoanToken( ITrueFiPool2 _pool, uint256 _amount, uint256 _term, uint256 _apy ) external override { require(_amount > 0, "LoanFactory: Loans of amount 0, will not be approved"); require(_term > 0, "LoanFactory: Loans cannot have instantaneous term of repay"); require(poolFactory.isPool(address(_pool)), "LoanFactory: Pool was not created by PoolFactory"); address newToken = address(new LoanToken2(_pool, msg.sender, lender, liquidator, _amount, _term, _apy)); isLoanToken[newToken] = true; emit LoanTokenCreated(newToken); } }
Internal function for loan repayment If _amount is sufficient, then this also settles the loan _sender account sending token to repay _amount amount of token to repay/
function _repay(address _sender, uint256 _amount) internal onlyAfterWithdraw { require(_amount <= debt.sub(_balance()), "LoanToken2: Cannot repay over the debt"); emit Repaid(_sender, _amount); token.safeTransferFrom(_sender, address(this), _amount); if (isRepaid()) { settle(); } }
1,718,048
./full_match/43114/0x54e1778e3E618429005dAeD5213791073B948C2D/sources/joe.sol
Total number of tokens Creates `_amount` token to `_to`. Must only be called by the owner (MasterJoe).
function mint(address _to, uint256 _amount) public onlyOwner { require( totalSupply().add(_amount) <= maxSupply, "JOE::mint: cannot exceed max supply" ); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); }
4,515,677
// This file is MIT Licensed. // // From: https://gist.githubusercontent.com/chriseth/f9be9d9391efc5beb9704255a8e2989d/raw/4d0fb90847df1d4e04d507019031888df8372239/snarktest.solidity // // Copyright 2017 Christian Reitwiessner // 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.14; library Curve { // p = p(u) = 36u^4 + 36u^3 + 24u^2 + 6u + 1 uint256 internal constant FIELD_ORDER = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47; // Number of elements in the field (often called `q`) // n = n(u) = 36u^4 + 36u^3 + 18u^2 + 6u + 1 uint256 internal constant GEN_ORDER = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; uint256 internal constant CURVE_B = 3; // a = (p+1) / 4 uint256 internal constant CURVE_A = 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52; struct G1Point { uint X; uint Y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint[2] X; uint[2] Y; } // (P+1) / 4 function A() pure internal returns (uint256) { return CURVE_A; } function P() pure internal returns (uint256) { return FIELD_ORDER; } function N() pure internal returns (uint256) { return GEN_ORDER; } /// @return the generator of G1 function P1() pure internal returns (G1Point) { return G1Point(1, 2); } function HashToPoint(uint256 s) internal constant returns (G1Point) { uint256 beta = 0; uint256 y = 0; // XXX: Gen Order (n) or Field Order (p) ? uint256 x = s % GEN_ORDER; while( true ) { (beta, y) = FindYforX(x); // y^2 == beta if( beta == mulmod(y, y, FIELD_ORDER) ) { return G1Point(x, y); } x = addmod(x, 1, FIELD_ORDER); } } /** * Given X, find Y * * where y = sqrt(x^3 + b) * * Returns: (x^3 + b), y */ function FindYforX(uint256 x) internal constant returns (uint256, uint256) { // beta = (x^3 + b) % p uint256 beta = addmod(mulmod(mulmod(x, x, FIELD_ORDER), x, FIELD_ORDER), CURVE_B, FIELD_ORDER); // y^2 = x^3 + b // this acts like: y = sqrt(beta) uint256 y = expMod(beta, CURVE_A, FIELD_ORDER); return (beta, y); } // a - b = c; function submod(uint a, uint b) internal pure returns (uint){ uint a_nn; if(a>b) { a_nn = a; } else { a_nn = a+GEN_ORDER; } return addmod(a_nn - b, 0, GEN_ORDER); } function expMod(uint256 _base, uint256 _exponent, uint256 _modulus) internal constant returns (uint256 retval) { bool success; uint256[1] memory output; uint[6] memory input; input[0] = 0x20; // baseLen = new(big.Int).SetBytes(getData(input, 0, 32)) input[1] = 0x20; // expLen = new(big.Int).SetBytes(getData(input, 32, 32)) input[2] = 0x20; // modLen = new(big.Int).SetBytes(getData(input, 64, 32)) input[3] = _base; input[4] = _exponent; input[5] = _modulus; assembly { success := staticcall(sub(gas, 2000), 5, input, 0xc0, output, 0x20) // Use "invalid" to make gas estimation work switch success case 0 { invalid } } require(success); return output[0]; } /// @return the generator of G2 function P2() pure internal returns (G2Point) { return G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); } function G() pure internal returns (G1Point) { return G1Point( 1, 2 ); } /// @return the negation of p, i.e. p.add(p.negate()) should be zero. function g1neg(G1Point p) pure internal returns (G1Point) { // The prime q in the base field F_q for G1 uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; if (p.X == 0 && p.Y == 0) return G1Point(0, 0); return G1Point(p.X, q - (p.Y % q)); } /// @return the sum of two points of G1 function g1add(G1Point p1, G1Point p2) constant internal returns (G1Point r) { uint[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success; assembly { success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid } } require(success); } /// @return the product of a point on G1 and a scalar, i.e. /// p == p.mul(1) and p.add(p) == p.mul(2) for all points p. function g1mul(G1Point p, uint s) constant internal returns (G1Point r) { uint[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; bool success; assembly { success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid } } require (success); } /// @return the result of computing the pairing check /// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should /// return true. function pairing(G1Point[] p1, G2Point[] p2) constant internal returns (bool) { require(p1.length == p2.length); uint elements = p1.length; uint inputSize = elements * 6; uint[] memory input = new uint[](inputSize); for (uint i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint[1] memory out; bool success; assembly { success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) // Use "invalid" to make gas estimation work switch success case 0 { invalid } } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2(G1Point a1, G2Point a2, G1Point b1, G2Point b2) constant internal returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } /// Convenience method for a pairing check for three pairs. function pairingProd3( G1Point a1, G2Point a2, G1Point b1, G2Point b2, G1Point c1, G2Point c2 ) constant internal returns (bool) { G1Point[] memory p1 = new G1Point[](3); G2Point[] memory p2 = new G2Point[](3); p1[0] = a1; p1[1] = b1; p1[2] = c1; p2[0] = a2; p2[1] = b2; p2[2] = c2; return pairing(p1, p2); } /// Convenience method for a pairing check for four pairs. function pairingProd4( G1Point a1, G2Point a2, G1Point b1, G2Point b2, G1Point c1, G2Point c2, G1Point d1, G2Point d2 ) constant internal returns (bool) { G1Point[] memory p1 = new G1Point[](4); G2Point[] memory p2 = new G2Point[](4); p1[0] = a1; p1[1] = b1; p1[2] = c1; p1[3] = d1; p2[0] = a2; p2[1] = b2; p2[2] = c2; p2[3] = d2; return pairing(p1, p2); } }
Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point a1, G2Point a2, G1Point b1, G2Point b2) constant internal returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); }
6,444,237
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressList { function add(address a) external returns (bool); function remove(address a) external returns (bool); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function length() external view returns (uint256); function grantRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressListFactory { function ours(address a) external view returns (bool); function listCount() external view returns (uint256); function listAt(uint256 idx) external view returns (address); function createList() external returns (address listaddr); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../bloq/IAddressList.sol"; interface IVesperPool is IERC20 { function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (IAddressList); function maintainers() external view returns (IAddressList); function feeCollector() external view returns (address); function pricePerShare() external view returns (uint256); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; interface IYToken { function balanceOf(address user) external view returns (uint256); function pricePerShare() external view returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit() external returns (uint256); function withdraw(uint256 shares) external returns (uint256); function token() external returns (address); function totalAssets() external view returns (uint256); function totalSupply() external view returns (uint256); function availableDepositLimit() external view returns (uint256); function decimals() external view returns (uint8); function withdrawalQueue(uint256 index) external view returns (address); function maxAvailableShares() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "../interfaces/bloq/ISwapManager.sol"; import "../interfaces/bloq/IAddressList.sol"; import "../interfaces/bloq/IAddressListFactory.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/vesper/IVesperPool.sol"; abstract contract Strategy is IStrategy, Context { using SafeERC20 for IERC20; IERC20 public immutable collateralToken; address public immutable receiptToken; address public immutable override pool; IAddressList public keepers; address public override feeCollector; ISwapManager public swapManager; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); constructor( address _pool, address _swapManager, address _receiptToken ) { require(_pool != address(0), "pool-address-is-zero"); require(_swapManager != address(0), "sm-address-is-zero"); swapManager = ISwapManager(_swapManager); pool = _pool; collateralToken = IERC20(IVesperPool(_pool).token()); receiptToken = _receiptToken; } modifier onlyGovernor { require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor"); _; } modifier onlyKeeper() { require(keepers.contains(_msgSender()), "caller-is-not-a-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-vesper-pool"); _; } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyGovernor { require(keepers.add(_keeperAddress), "add-keeper-failed"); } /** * @notice Create keeper list * NOTE: Any function with onlyKeeper modifier will not work until this function is called. * NOTE: Due to gas constraint this function cannot be called in constructor. * @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param * ethereum- 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3 * polygon-0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291 */ function init(address _addressListFactory) external onlyGovernor { require(address(keepers) == address(0), "keeper-list-already-created"); // Prepare keeper list IAddressListFactory _factory = IAddressListFactory(_addressListFactory); keepers = IAddressList(_factory.createList()); require(keepers.add(_msgSender()), "add-keeper-failed"); } /** * @notice Migrate all asset and vault ownership,if any, to new strategy * @dev _beforeMigration hook can be implemented in child strategy to do extra steps. * @param _newStrategy Address of new strategy */ function migrate(address _newStrategy) external virtual override onlyPool { require(_newStrategy != address(0), "new-strategy-address-is-zero"); require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy"); _beforeMigration(_newStrategy); IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this))); collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this))); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyGovernor { require(keepers.remove(_keeperAddress), "remove-keeper-failed"); } /** * @notice Update fee collector * @param _feeCollector fee collector address */ function updateFeeCollector(address _feeCollector) external onlyGovernor { require(_feeCollector != address(0), "fee-collector-address-is-zero"); require(_feeCollector != feeCollector, "fee-collector-is-same"); emit UpdatedFeeCollector(feeCollector, _feeCollector); feeCollector = _feeCollector; } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyGovernor { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } /// @dev Approve all required tokens function approveToken() external onlyKeeper { _approveToken(0); _approveToken(MAX_UINT_VALUE); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyPool { _withdraw(_amount); } /** * @dev Rebalance profit, loss and investment of this strategy */ function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); } /** * @dev sweep given token to feeCollector of strategy * @param _fromToken token address to sweep */ function sweepERC20(address _fromToken) external override onlyKeeper { require(feeCollector != address(0), "fee-collector-not-set"); require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral"); require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(feeCollector), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(feeCollector, _amount); } } /// @notice Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /// @dev Convert from 18 decimals to token defined decimals. Default no conversion. function convertFrom18(uint256 amount) public pure virtual returns (uint256) { return amount; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() external view virtual override returns (uint256 _value); /// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy * @param _newStrategy . */ function _beforeMigration(address _newStrategy) internal virtual; /** * @notice Generate report for current profit and loss. Also liquidate asset to payback * excess debt, if any. * @return _profit Calculate any realized profit and convert it to collateral, if not already. * @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token. * @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt. */ function _generateReport() internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); _profit = _realizeProfit(_totalDebt); _loss = _realizeLoss(_totalDebt); _payback = _liquidate(_excessDebt); } /** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * @param _from address of from token * @param _to address of to token * @param _amountIn Amount to be swapped * @param _minAmountOut minimum acceptable return amount */ function _safeSwap( address _from, address _to, uint256 _amountIn, uint256 _minAmountOut ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amountIn); if (_minAmountOut == 0) _minAmountOut = 1; if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amountIn, _minAmountOut, path, address(this), block.timestamp ); } } function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; // Some strategies may not have rewards hence they do not need this function. //solhint-disable-next-line no-empty-blocks function _claimRewardsAndConvertTo(address _toToken) internal virtual {} /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback); /** * @notice Calculate earning and withdraw/convert it into collateral token. * @param _totalDebt Total collateral debt of this strategy * @return _profit Profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit); /** * @notice Calculate loss * @param _totalDebt Total collateral debt of this strategy * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss); /** * @notice Reinvest collateral. * @dev Once we file report back in pool, we might have some collateral in hand * which we want to reinvest aka deposit in lender/provider. */ function _reinvest() internal virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../Strategy.sol"; import "../../interfaces/yearn/IYToken.sol"; /// @title This strategy will deposit collateral token in a Yearn vault and earn interest. abstract contract YearnStrategy is Strategy { using SafeERC20 for IERC20; IYToken internal immutable yToken; constructor( address _pool, address _swapManager, address _receiptToken ) Strategy(_pool, _swapManager, _receiptToken) { require(_receiptToken != address(0), "yToken-address-is-zero"); yToken = IYToken(_receiptToken); } /** * @notice Calculate total value using underlying yToken * @dev Report total value in collateral token */ function totalValue() external view override returns (uint256 _totalValue) { _totalValue = _getCollateralBalance(); } function isReservedToken(address _token) public view override returns (bool) { return _token == address(yToken); } /// @notice Approve all required tokens function _approveToken(uint256 _amount) internal override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(yToken), _amount); } /** * @notice Before migration hook. no rewards, so empty implementation * @param _newStrategy Address of new strategy. */ //solhint-disable-next-line no-empty-blocks function _beforeMigration(address _newStrategy) internal override {} /// @notice Withdraw collateral to payback excess debt function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) { if (_excessDebt != 0) { _payback = _safeWithdraw(_excessDebt); } } /** * @notice Calculate earning and withdraw it from Yearn. * @param _totalDebt Total collateral debt of this strategy * @return profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal override returns (uint256) { uint256 _collateralBalance = _getCollateralBalance(); if (_collateralBalance > _totalDebt) { _withdrawHere(_collateralBalance - _totalDebt); } return collateralToken.balanceOf(address(this)); } /** * @notice Calculate realized loss. * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) { uint256 _collateralBalance = _getCollateralBalance(); if (_collateralBalance < _totalDebt) { _loss = _totalDebt - _collateralBalance; } } /// @notice Deposit collateral in Yearn vault function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); if (_collateralBalance != 0) { yToken.deposit(_collateralBalance); } } /// @dev Withdraw collateral and transfer it to pool function _withdraw(uint256 _amount) internal override { _safeWithdraw(_amount); collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this))); } /** * @notice Safe withdraw will make sure to check asking amount against available amount. * @param _amount Amount of collateral to withdraw. * @return Actual collateral withdrawn */ function _safeWithdraw(uint256 _amount) internal returns (uint256) { uint256 _collateralBalance = _getCollateralBalance(); // Get minimum of _amount and _collateralBalance return _withdrawHere(_amount < _collateralBalance ? _amount : _collateralBalance); } /// @dev Withdraw collateral here. Do not transfer to pool function _withdrawHere(uint256 _amount) internal returns (uint256) { // Returns the exact collateral amount withdrawed from yVault return yToken.withdraw(_convertToShares(_amount)); } /// @dev Gets collateral balance into yVault function _getCollateralBalance() internal view returns (uint256) { return (yToken.balanceOf(address(this)) * yToken.pricePerShare()) / (10**yToken.decimals()); } /// @dev Converts a collateral amount in its relative shares for yVault function _convertToShares(uint256 _collateralAmount) internal view returns (uint256) { return (_collateralAmount * (10**yToken.decimals())) / yToken.pricePerShare(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./YearnStrategy.sol"; // solhint-disable no-empty-blocks /// @title Deposit DAI in Yearn's DAI yVault and earn interest. contract YearnStrategyDAI is YearnStrategy { string public constant NAME = "Yearn-Strategy-DAI"; string public constant VERSION = "3.0.0"; // yvDAI = 0x19D3364A399d251E894aC732651be8B0E4e85001 constructor(address _pool, address _swapManager) YearnStrategy(_pool, _swapManager, 0x19D3364A399d251E894aC732651be8B0E4e85001) {} }
Approve all required tokens
function _approveToken(uint256 _amount) internal override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(yToken), _amount); }
10,367,768
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many 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 HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private {
14,087,539
// File: contracts\token\ERC721\IERC721Metadata.sol // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.5; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts\access\AccessControl.sol /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev 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 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 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; } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor() { _registerInterface(_INTERFACE_ID_ERC165); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract Decurly is ERC165, Context, Ownable { using ECDSA for bytes32; using Strings for uint256; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x6352211e; mapping(address => bool) private _minters; struct OwnerInfo { address owner; uint32 ttl; uint32 timestamp; bool DNSSEC; string domain; } mapping(uint256 => OwnerInfo) private _tokenOwners; mapping(address => uint256) private _defaultDomain; string private _name; string private _symbol; string private _baseURI; uint8 private _maxTrustScore; uint256 private _chainId; event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); constructor( string memory name_, string memory symbol_, string memory baseURI_ ) { _name = name_; _symbol = symbol_; _baseURI = baseURI_; addMinter(_msgSender()); _maxTrustScore = 95; _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721); fetchChainId(); } /* * Gets the owner of a tokenId */ function ownerOf(uint256 tokenId) public view virtual returns (address) { return _tokenOwners[tokenId].owner; } function _mint( string memory domain, address to, uint32 ttl, uint256 id, bool DNSSEC, bool setAsDefault, uint32 timestamp ) private { OwnerInfo memory ownerInfo = _tokenOwners[id]; address tOwner = ownerInfo.owner; if (tOwner != to) { ownerInfo.domain = domain; ownerInfo.owner = to; if (_defaultDomain[tOwner] == id) { _defaultDomain[tOwner] = 0; } ownerInfo.timestamp = timestamp; emit Transfer(tOwner, to, id); } if (setAsDefault && _defaultDomain[to] != id) { _defaultDomain[to] = id; } ownerInfo.DNSSEC = DNSSEC; ownerInfo.ttl = ttl; _tokenOwners[id] = ownerInfo; } /* * Minting should only be possible: * - Signer has minter role. * - parameters are signed correctly * - Ticket was not already used. * - ttl is valid * Idea: * We could save some space by converting domain to a base38 encoding * Saving 2-Bit per domain-Character (Allowed domain Characters are [a-z] (lowercase is enough) [0-9] and [.-]) * on a theoretical length of 256 Byte we would save two SSTORE operations */ function mint( string memory domain, address to, uint32 ttl, uint256 id, bytes32 r, bytes32 s, uint8 v, bool DNSSEC, bool setAsDefault ) external payable { require(ttl >= block.timestamp, "Error:Old ticket"); require(_tokenOwners[id].ttl < ttl, "Error:Already used"); bytes32 hashed = keccak256( abi.encodePacked( domain, to, id, ttl, msg.value, DNSSEC, setAsDefault, _chainId ) ); require(_minters[hashed.recover(v, r, s)] == true, "Error:Unsigned tx"); _mint( domain, to, ttl, id, DNSSEC, setAsDefault, uint32(block.timestamp) ); } // EVM has chainId function fetchChainId() public onlyOwner { _chainId = _getChainId(); } // in case there is no chainId on the EVM i have to come up with one... function setChainId(uint256 id) external onlyOwner { _chainId = id; } /* * To save users minting costs, the transfer of current contract holdings ist done owner * This saves an unneccessary transfer in the minting process. */ function withdraw() external onlyOwner { require(payable(msg.sender).send(address(this).balance)); } /* * Multichain.... */ function _getChainId() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /* * Burns domain token if you want to get rid of it */ function burn(uint256 id) public { require(ownerOf(id) == msg.sender, "Error: you have to be Owner"); _tokenOwners[id].owner = address(0); if (_defaultDomain[msg.sender] != 0) { delete _defaultDomain[msg.sender]; } emit Transfer(msg.sender, address(0), id); } /* * Gets default domain for address */ function getDefaultDomain(address adr) external view returns (string memory domain) { uint256 id = _defaultDomain[adr]; require(adr != address(0), "Error: No default for null address"); require(ownerOf(id) == adr, "Error: No default domain"); return _tokenOwners[id].domain; } /* * Sets default domaintoken for address */ function setDefaultDomainToken(uint256 id) external { require(ownerOf(id) == msg.sender, "Error: Not owner of domain"); _defaultDomain[msg.sender] = id; } /* * Resets domaintoken for address */ function resetDefaultDomainToken() external { _defaultDomain[msg.sender] = 0; } /* * Gets tokenId for a given domain (Punycoded) */ function getDomainTokenId(string memory domain) public pure returns (uint256 tokenId) { return uint256(keccak256(abi.encodePacked(domain))); } /* * Gets domainstring for the token */ function getDomainOfToken(uint256 tokenId) public view returns (string memory domain) { return _tokenOwners[tokenId].domain; } /* * Gets the owner wallet of the domain */ function getDomainOwner(string memory domain) public view returns (address owner) { return ownerOf(getDomainTokenId(domain)); } /* * Tokenname */ function name() public view returns (string memory) { return _name; } /* * Tokensymbol */ function symbol() public view returns (string memory) { return _symbol; } /* * TokenUri */ function tokenURI(uint256 tokenId) public view returns (string memory) { require( ownerOf(tokenId) != address(0), "ERC721Metadata: URI query for nonexistent token" ); return string( abi.encodePacked( baseURI(), _chainId.toString(), "/", tokenId.toString() ) ); } /* * FFU => SET 100 once DNSSEC verification is implemented */ function setCurrentMaxTrustScore(uint8 score) external onlyOwner { _maxTrustScore = score; } /* * Gives you the current max trustScore reachable (DNSSEC is not implemented yet) */ function getCurrentMaxTrustScore() public view returns (uint8) { return _maxTrustScore; } /* * See getTrustScore(uint256 id) but domain-string based */ function getTrustScore(string memory domain) public view returns (uint256) { return getTrustScore(getDomainTokenId(domain)); } /* * Gets a trustScore (0 - 100) for a domain * DNSSEC Domains are 100 * * NON DNSSEC domain are 0 - 95 (Zero at day one and 90 at day 9) * Final value of non-DNSSEC domains is 95 after day 10. * If you want some security on non DNSSEC entries you might consider that in a case of a broad DNS-Spoofing attack * it could probably last about one to five days in normal cases. * If you have critical payments on chain, implement the getTrustScore accordingly! */ function getTrustScore(uint256 id) public view returns (uint256) { require(ownerOf(id) != address(0), "Error: id has no owner"); if (_tokenOwners[id].DNSSEC) { return 100; } uint256 sinceInception = block.timestamp - _tokenOwners[id].timestamp; uint256 daysSinceInception = sinceInception / 86400; if (daysSinceInception > 9) { return 95; } else { return daysSinceInception * 10; } } function setBaseURI(string memory baseURI_) public onlyOwner { _baseURI = baseURI_; } function baseURI() public view returns (string memory) { return _baseURI; } /* adds a minter role */ function addMinter(address minter_) public onlyOwner { _minters[minter_] = true; } /* removes a minter role */ function removeMinter(address minter_) public onlyOwner { _minters[minter_] = false; } }
Gets the owner of a tokenId/
function ownerOf(uint256 tokenId) public view virtual returns (address) { return _tokenOwners[tokenId].owner; }
11,952,421
./full_match/421613/0x1C8959eC205bb7663Da438F505079E2b412d888B/sources/src/staking/StakedERC721.sol
Calculates the rewards for specific tokens under an address account - account to check tokenIds - token ids to check against return rewards/
function calculateRewards( address account, uint256[] memory tokenIds ) external view returns (uint256[] memory rewards) { rewards = new uint256[](tokenIds.length); for (uint256 i; i < tokenIds.length; i++) { rewards[i] = _calculateReward(account, tokenIds[i]); } return rewards; }
11,565,273
./full_match/80001/0x3a5AFce26bc4ba6bdeC6C15533Ef74F1e5D994B3/sources/contracts/IERC721.sol
Required interface of an ERC721 compliant contract./
interface IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function totalSupply() external view returns (uint256 _totalSupply); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function setApprovalForAll(address operator, bool approved) external; function getApproved( uint256 tokenId ) external view returns (address operator); function isApprovedForAll( address owner, address operator ) external view returns (bool); }
9,521,562
// 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: 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; /** * @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: 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 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: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT AND Apache-2.0 pragma solidity 0.7.6; import '../interfaces/IERC20.sol'; import '../utils/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); _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: 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 '@openzeppelin/contracts/utils/Context.sol'; import '../../0xerc1155/interfaces/IERC1155.sol'; import '../../0xerc1155/interfaces/IERC1155TokenReceiver.sol'; import '../../0xerc1155/utils/SafeMath.sol'; import '../investment/interfaces/ICFolioFarm.sol'; // WOWS rewards import '../token/interfaces/IWOWSERC1155.sol'; // SFT contract import '../token/interfaces/IWOWSCryptofolio.sol'; import '../utils/AddressBook.sol'; import '../utils/interfaces/IAddressRegistry.sol'; import '../utils/TokenIds.sol'; import './interfaces/ICFolioItemBridge.sol'; import './interfaces/ICFolioItemHandler.sol'; import './interfaces/ISFTEvaluator.sol'; /** * @dev CFolioItemHandlerFarm manages CFolioItems, minted in the SFT contract. * * Minting CFolioItem SFTs is implemented in the WOWSSFTMinter contract, which * mints the SFT in the WowsERC1155 contract and calls setupCFolio in here. * * Normaly CFolioItem SFTs are locked in the main TradeFloor contract to allow * trading or transfer into a Base SFT card's c-folio. * * CFolioItem SFTs only earn rewards if they are inside the cfolio of a base * NFT. We get called from main TradeFloor every time an CFolioItem gets * transfered and calculate the new rewardable amount based on the reward % * of the base NFT. */ abstract contract CFolioItemHandlerFarm is ICFolioItemHandler, Context { using SafeMath for uint256; using TokenIds for uint256; ////////////////////////////////////////////////////////////////////////////// // Routing ////////////////////////////////////////////////////////////////////////////// // Route to SFT Minter. Only setup from SFT Minter allowed. address public sftMinter; // The TradeFloor contract which provides c-folio NFTs. This TradeFloor // contract calls the IMinterCallback interface functions. ICFolioItemBridge public immutable cfiBridge; // SFT evaluator ISFTEvaluator public immutable sftEvaluator; // Reward emitter ICFolioFarmOwnable public immutable cfolioFarm; // Admin address public immutable admin; // The SFT contract needed to check if the address is a c-folio IWOWSERC1155 public immutable sftHolder; ////////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////////// /* * @dev Emitted when a reward is updated, either increased or decreased * * @param previousAmount The amount before updating the reward * @param newAmount The amount after updating the reward */ event RewardUpdated(uint256 previousAmount, uint256 newAmount); /** * @dev Emitted when a new minter is set by the admin * * @param minter The new minter */ event NewMinter(address minter); /** * @dev Emitted when the contract is destructed * * @param thisContract The address of this contract */ event CFolioItemHandlerDestructed(address thisContract); ////////////////////////////////////////////////////////////////////////////// // Modifiers ////////////////////////////////////////////////////////////////////////////// modifier onlyBridge() { require(_msgSender() == address(cfiBridge), 'CFHI: Only CFIB'); _; } modifier onlyAdmin() { require(_msgSender() == admin, 'CFIH: Only admin'); _; } ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev Constructs the CFolioItemHandlerFarm * * We gather all current addresses from address registry into immutable vars. * If one of the relevant addresses changes, the contract has to be updated. * There is little state here, user state is completely handled in CFolioFarm. */ constructor(IAddressRegistry addressRegistry, bytes32 rewardFarmKey) { // TradeFloor cfiBridge = ICFolioItemBridge( addressRegistry.getRegistryEntry(AddressBook.CFOLIOITEM_BRIDGE_PROXY) ); // Admin admin = addressRegistry.getRegistryEntry(AddressBook.MARKETING_WALLET); // The SFT holder sftHolder = IWOWSERC1155( addressRegistry.getRegistryEntry(AddressBook.SFT_HOLDER) ); // The SFT minter sftMinter = addressRegistry.getRegistryEntry(AddressBook.SFT_MINTER); emit NewMinter(sftMinter); // SFT evaluator sftEvaluator = ISFTEvaluator( addressRegistry.getRegistryEntry(AddressBook.SFT_EVALUATOR_PROXY) ); // WOWS rewards cfolioFarm = ICFolioFarmOwnable( addressRegistry.getRegistryEntry(rewardFarmKey) ); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ICFolioItemCallback} via {ICFolioItemHandler} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ICFolioItemCallback-onCFolioItemsTransferedFrom} */ function onCFolioItemsTransferedFrom( address from, address to, uint256[] calldata, /* tokenIds*/ address[] calldata /* cfolioHandlers*/ ) external override onlyBridge { // In case of transfer verify the target uint256 sftTokenId; if ( to != address(0) && (sftTokenId = sftHolder.addressToTokenId(to)) != uint256(-1) ) { _verifyTransferTarget(sftTokenId); _updateRewards(to, sftEvaluator.rewardRate(sftTokenId)); } if ( from != address(0) && (sftTokenId = sftHolder.addressToTokenId(from)) != uint256(-1) ) { _updateRewards(from, sftEvaluator.rewardRate(sftTokenId)); } } /** * @dev See {ICFolioItemCallback-appendHash} */ function appendHash(address cfolioItem, bytes calldata current) external view override returns (bytes memory) { return abi.encodePacked( current, address(this), cfolioFarm.balanceOf(cfolioItem) ); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ICFolioItemHandler} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ICFolioItemHandler-sftUpgrade} */ function sftUpgrade(uint256 tokenId, uint32 newRate) external override { // Validate access require(_msgSender() == address(sftEvaluator), 'CFIH: Invalid caller'); require(tokenId.isBaseCard(), 'CFIH: Invalid token'); // CFolio address address cfolio = sftHolder.tokenIdToAddress(tokenId); // Update state _updateRewards(cfolio, newRate); } /** * @dev See {ICFolioItemHandler-setupCFolio} * * Note: We place a dummy ERC1155 token with ID 0 into the CFolioItem's * c-folio. The reason is that we want to know if a c-folio item gets burned, * as burning an empty c-folio will result in no transfers. This prevents * tokens from becoming inaccessible. * * Refer to the Minimal ERC1155 section below to learn which functions are * needed for this. */ function setupCFolio( address payer, uint256 sftTokenId, uint256[] calldata amounts ) external override { // Validate access require(_msgSender() == sftMinter, 'CFIH: Only sftMinter'); // Validate parameters, no unmasking required, must be SFT address cFolio = sftHolder.tokenIdToAddress(sftTokenId); require(cFolio != address(0), 'CFIH: No cfolio'); // Verify that this function is called the first time (, uint256 length) = IWOWSCryptofolio(cFolio).getCryptofolio(address(this)); require(length == 0, 'CFIH: Not empty'); // Transfer a dummy NFT token to cFolio so we get informed if the cFolio // gets burned IERC1155TokenReceiver(cFolio).onERC1155Received( address(this), address(0), 0, 1, '' ); if (amounts.length > 0) { _deposit(cFolio, payer, amounts); } } /** * @dev See {ICFolioItemHandler-deposit} * * Note: tokenId can be owned by a base SFT * In this case base SFT cannot be locked * * There is only need to update rewards if tokenId * is part of an unlocked base SFT */ function deposit( uint256 baseTokenId, uint256 tokenId, uint256[] calldata amounts ) external override { // Validate parameters (address baseCFolio, address itemCFolio) = _verifyAssetAccess( baseTokenId, tokenId ); // Call the implementation _deposit(itemCFolio, _msgSender(), amounts); // Update rewards if CFI is inside cfolio if (baseCFolio != address(0)) _updateRewards(baseCFolio, sftEvaluator.rewardRate(baseTokenId)); } /** * @dev See {ICFolioItemHandler-withdraw} * * Note: tokenId can be owned by a base SFT. In this case, the base SFT * cannot be locked. * * There is only need to update rewards if tokenId is part of an unlocked * base SFT. */ function withdraw( uint256 baseTokenId, uint256 tokenId, uint256[] calldata amounts ) external override { // Validate parameters (address baseCFolio, address itemCFolio) = _verifyAssetAccess( baseTokenId, tokenId ); // Call the implementation _withdraw(itemCFolio, amounts); // Update rewards if CFI is inside cfolio if (baseCFolio != address(0)) _updateRewards(baseCFolio, sftEvaluator.rewardRate(baseTokenId)); } /** * @dev See {ICFolioItemHandler-getRewards} * * Note: tokenId must be a base SFT card * * We allow reward pull only for unlocked SFTs. */ function getRewards(address recipient, uint256 tokenId) external override { // Validate parameters require(recipient != address(0), 'CFIH: Invalid recipient'); require(tokenId.isBaseCard(), 'CFIH: Invalid tokenId'); // Verify that tokenId has a valid cFolio address uint256 sftTokenId = tokenId.toSftTokenId(); address cfolio = sftHolder.tokenIdToAddress(sftTokenId); require(cfolio != address(0), 'CFHI: No cfolio'); // Verify that the tokenId is owned by msg.sender in case of direct // call or recipient in case of sftMinter call in the SFT contract. // This also verifies that the token is not locked in TradeFloor. require( IERC1155(address(sftHolder)).balanceOf(_msgSender(), sftTokenId) == 1 || (_msgSender() == sftMinter && IERC1155(address(sftHolder)).balanceOf(recipient, sftTokenId) == 1), 'CFHI: Forbidden' ); cfolioFarm.getReward(cfolio, recipient); } /** * @dev See {ICFolioItemHandler-getRewardInfo} */ function getRewardInfo(uint256[] calldata tokenIds) external view override returns (bytes memory result) { uint256[5] memory uiData; // Get basic data once uiData = cfolioFarm.getUIData(address(0)); // total / rewardDuration / rewardPerDuration result = abi.encodePacked(uiData[0], uiData[2], uiData[3]); uint256 length = tokenIds.length; if (length > 0) { // Iterate through all tokenIds and collect reward info for (uint256 i = 0; i < length; ++i) { uint256 sftTokenId = tokenIds[i].toSftTokenId(); uint256 share = 0; uint256 earned = 0; if (sftTokenId.isBaseCard()) { address cfolio = sftHolder.tokenIdToAddress(sftTokenId); if (cfolio != address(0)) { uiData = cfolioFarm.getUIData(cfolio); share = uiData[1]; earned = uiData[4]; } } result = abi.encodePacked(result, share, earned); } } } ////////////////////////////////////////////////////////////////////////////// // Internal interface ////////////////////////////////////////////////////////////////////////////// /** * @dev Deposit amounts */ function _deposit( address itemCFolio, address payer, uint256[] calldata amounts ) internal virtual; /** * @dev Withdraw amounts */ function _withdraw(address itemCFolio, uint256[] calldata amounts) internal virtual; /** * @dev Verify if target base SFT is allowed */ function _verifyTransferTarget(uint256 baseSftTokenId) internal virtual; ////////////////////////////////////////////////////////////////////////////// // Maintanace ////////////////////////////////////////////////////////////////////////////// /** * @dev Destruct implementation */ function selfDestruct() external onlyAdmin { // Dispatch event CFolioItemHandlerDestructed(address(this)); // Disable high-impact Slither detector "suicidal" here. Slither explains // that "CFolioItemHandlerFarm.selfDestruct() allows anyone to destruct the // contract", which is not the case due to the onlyAdmin modifier. // // slither-disable-next-line suicidal selfdestruct(payable(admin)); } /** * @dev Set a new SFT minter */ function setMinter(address newMinter) external onlyAdmin { // Validate parameters require(newMinter != address(0), 'CFIH: Invalid'); // Update state sftMinter = newMinter; // Dispatch event emit NewMinter(newMinter); } ////////////////////////////////////////////////////////////////////////////// // Minimal ERC1155 implementation (called from SFTBase CFolio) ////////////////////////////////////////////////////////////////////////////// // We do nothing for our dummy burn tokenId function setApprovalForAll(address, bool) external {} // Check for length == 1, and then return always 1 function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external pure returns (uint256[] memory) { // Validate parameters require(_owners.length == 1 && _ids.length == 1, 'CFIH: Must be 1'); uint256[] memory result = new uint256[](1); result[0] = 1; return result; } /** * @dev We don't allow burning non-empty c-folios */ function burnBatch( address, /* account */ uint256[] calldata tokenIds, uint256[] calldata ) external view { // Validate parameters require(tokenIds.length == 1, 'CFIH: Must be 1'); // This call originates from the c-folio. We revert if there are investment // amounts left for this c-folio address. require(cfolioFarm.balanceOf(_msgSender()) == 0, 'CFIH: Not empty'); } ////////////////////////////////////////////////////////////////////////////// // Internal details ////////////////////////////////////////////////////////////////////////////// /** * @dev Run through all cFolioItems collected in cFolio and select the amount * of tokens. Update cfolioFarm. */ function _updateRewards(address cfolio, uint32 rate) private { // Get c-folio items of this base cFolio (uint256[] memory tokenIds, uint256 length) = IWOWSCryptofolio(cfolio) .getCryptofolio(address(cfiBridge)); // Marginal increase in gas per item is around 25K. Bounding items to 100 // fits in sensible gas limits. require(length <= 100, 'CFIH: Too many items'); // Calculate new reward amount uint256 newRewardAmount = 0; for (uint256 i = 0; i < length; ++i) { address secondaryCFolio = sftHolder.tokenIdToAddress(tokenIds[i]); require(secondaryCFolio != address(0), 'CFIH: Invalid tokenId'); if (IWOWSCryptofolio(secondaryCFolio)._tradefloors(0) == address(this)) newRewardAmount = newRewardAmount.add( cfolioFarm.balanceOf(secondaryCFolio) ); } newRewardAmount = newRewardAmount.mul(rate).div(1E6); // Calculate existing reward amount uint256 exitingRewardAmount = cfolioFarm.balanceOf(cfolio); // Compare amounts and add/remove shares if (newRewardAmount > exitingRewardAmount) { // Update state cfolioFarm.addShares(cfolio, newRewardAmount.sub(exitingRewardAmount)); // Dispatch event emit RewardUpdated(exitingRewardAmount, newRewardAmount); } else if (newRewardAmount < exitingRewardAmount) { // Update state cfolioFarm.removeShares(cfolio, exitingRewardAmount.sub(newRewardAmount)); // Dispatch event emit RewardUpdated(exitingRewardAmount, newRewardAmount); } } /** * @dev Verifies if an asset access operation is allowed * * @param baseTokenId Base card tokenId or uint(-1) * @param cfolioItemTokenId CFolioItem tokenId handled by this contract * * A tokenId is "unlocked" if msg.sender is the owner of a tokenId in SFT * contract. If baseTokenId is uint(-1), cfolioItemTokenId has to be be * unlocked, otherwise baseTokenId has to be unlocked and the locked * cfolioItemTokenId has to be inside its c-folio. */ function _verifyAssetAccess(uint256 baseTokenId, uint256 cfolioItemTokenId) private view returns (address, address) { // Verify it's a cfolioItemTokenId require(cfolioItemTokenId.isCFolioCard(), 'CFHI: Not cFolioCard'); // Verify that the tokenId is one of ours address cFolio = sftHolder.tokenIdToAddress( cfolioItemTokenId.toSftTokenId() ); require(cFolio != address(0), 'CFIH: Invalid cFolioTokenId'); require( IWOWSCryptofolio(cFolio)._tradefloors(0) == address(this), 'CFIH: Not our SFT' ); address baseCFolio = address(0); if (baseTokenId != uint256(-1)) { // Verify it's a c-folio base card require(baseTokenId.isBaseCard(), 'CFHI: Not baseCard'); baseCFolio = sftHolder.tokenIdToAddress(baseTokenId.toSftTokenId()); require(baseCFolio != address(0), 'CFIH: Invalid baseCFolioTokenId'); // Verify that the tokenId is owned by msg.sender in SFT contract. // This also verifies that the token is not locked in TradeFloor. require( IERC1155(address(sftHolder)).balanceOf(_msgSender(), baseTokenId) == 1, 'CFHI: Access denied (B)' ); // Verify that the cfiTokenId is owned by given baseCFolio. // In V2 we have unlocked CFIs in baseCfolio in contrast to V1 require( cfiBridge.balanceOf(baseCFolio, cfolioItemTokenId) == 1, 'CFHI: Access denied (CF)' ); } else { // Verify that the tokenId is owned by msg.sender in SFT contract. // This also verifies that the token is not locked in TradeFloor. require( IERC1155(address(sftHolder)).balanceOf( _msgSender(), cfolioItemTokenId ) == 1, 'CFHI: Access denied' ); } return (baseCFolio, cFolio); } } /* * 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/utils/SafeERC20.sol'; import './CFolioItemHandlerFarm.sol'; /** * @dev CFolioItemHandlerLP manages CFolioItems, minted in the SFT contract. * * See {CFolioItemHandlerFarm}. */ contract CFolioItemHandlerLP is CFolioItemHandlerFarm { using SafeERC20 for IERC20; ////////////////////////////////////////////////////////////////////////////// // Routing ////////////////////////////////////////////////////////////////////////////// // The token staked here (WOWS/WETH UniV2 Pair) IERC20 public immutable stakingToken; ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev Constructs the CFolioItemHandlerLP * * We gather all current addresses from address registry into immutable vars. * If one of the relevant addresses changes, the contract has to be updated. * There is little state here, user state is completely handled in CFolioFarm. */ constructor(IAddressRegistry addressRegistry) CFolioItemHandlerFarm(addressRegistry, AddressBook.WOLVES_REWARDS) { // The ERC-20 token we stake stakingToken = IERC20( addressRegistry.getRegistryEntry(AddressBook.UNISWAP_V2_PAIR) ); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {CFolioItemHandlerFarm} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {CFolioItemHandlerFarm-_deposit}. */ function _deposit( address itemCFolio, address payer, uint256[] calldata amounts ) internal override { // Validate parameters require(amounts.length == 1 && amounts[0] > 0, 'CFIHLP: invalid amount'); // Transfer LP token to this contract stakingToken.safeTransferFrom(payer, address(this), amounts[0]); // Record assets in the Farm contract. They don't earn rewards. // // NOTE: {addAssets} must only be called from investment CFolios. cfolioFarm.addAssets(itemCFolio, amounts[0]); } /** * @dev See {CFolioItemHandlerFarm-_withdraw}. */ function _withdraw(address itemCFolio, uint256[] calldata amounts) internal override { // Validate parameters require(amounts.length == 1 && amounts[0] > 0, 'CFIHLP: invalid amount'); // Record assets in Farm contract. They don't earn rewards. // // NOTE: {removeAssets} must only be called from Investment CFolios. cfolioFarm.removeAssets(itemCFolio, amounts[0]); // Transfer LP token from this contract. stakingToken.safeTransfer(_msgSender(), amounts[0]); } /** * @dev Verify if target base SFT is allowed */ function _verifyTransferTarget(uint256 baseSftTokenId) internal view override { (, uint8 level) = sftHolder.getTokenData(baseSftTokenId); require((LEVEL2WOLF & (uint256(1) << level)) > 0, 'CFIHLP: Wolves only'); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ICFolioItemHandler} via {CFolioItemHandlerFarm} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ICFolioItemHandler-getAmounts} */ function getAmounts(address cfolioItem) external view override returns (uint256[] memory) { uint256[] memory result = new uint256[](1); result[0] = cfolioFarm.balanceOf(cfolioItem); return result; } } /* * 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 C-folio item bridge */ interface ICFolioItemBridge { /** * @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 tokenIds IDs of each token type * @param amounts Transfer amounts per token type */ function safeBatchTransferFrom( address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory ) external; /** * @notice Burn multiple types of tokens from the from * @param from Source addresses * @param tokenIds IDs of each token type * @param amounts Transfer amounts per token type */ function burnBatch( address from, uint256[] calldata tokenIds, uint256[] calldata amounts ) external; /** * @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) 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); /** * @notice Get the balance of single account/token pair * @param account The address of the token holders * @param tokenId ID of the token * @return The account's balance (0 or 1) */ function balanceOf(address account, uint256 tokenId) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param accounts The addresses of the token holders * @param tokenIds ID of the Tokens * @return The accounts's balances (0 or 1) */ function balanceOfBatch(address[] memory accounts, uint256[] memory tokenIds) external view returns (uint256[] 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 LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; import '../../token/interfaces/ICFolioItemCallback.sol'; /** * @dev Interface to C-folio item contracts */ interface ICFolioItemHandler is ICFolioItemCallback { /** * @dev Called when a SFT tokens grade needs re-evaluation * * @param tokenId The ERC-1155 token ID. Rate is in 1E6 convention: 1E6 = 100% * @param newRate The new value rate */ function sftUpgrade(uint256 tokenId, uint32 newRate) external; /** * @dev Called from SFTMinter after an Investment SFT is minted * * @param payer The approved address to get investment from * @param sftTokenId The sftTokenId whose c-folio is the owner of investment * @param amounts The amounts of invested assets */ function setupCFolio( address payer, uint256 sftTokenId, uint256[] calldata amounts ) external; ////////////////////////////////////////////////////////////////////////////// // Asset access ////////////////////////////////////////////////////////////////////////////// /** * @dev Adds investments into a cFolioItem SFT * * Transfers amounts of assets from users wallet to the contract. In general, * an Approval call is required before the function is called. * * @param baseTokenId cFolio tokenId, must be unlocked, or -1 * @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio * @param amounts Investment amounts, implementation specific */ function deposit( uint256 baseTokenId, uint256 tokenId, uint256[] calldata amounts ) external; /** * @dev Removes investments from a cFolioItem SFT * * Withdrawn token are transfered back to msg.sender. * * @param baseTokenId cFolio tokenId, must be unlocked, or -1 * @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio * @param amounts Investment amounts, implementation specific */ function withdraw( uint256 baseTokenId, uint256 tokenId, uint256[] calldata amounts ) external; /** * @dev Get the rewards collected by an SFT base card * * @param recipient Recipient of the rewards (- fees) * @param tokenId SFT base card tokenId, must be unlocked */ function getRewards(address recipient, uint256 tokenId) external; /** * @dev Get amounts (handler specific) for a cfolioItem * * @param cfolioItem address of CFolioItem contract */ function getAmounts(address cfolioItem) external view returns (uint256[] memory); /** * @dev Get information obout the rewardFarm * * @param tokenIds List of basecard tokenIds * @return bytes of uint256[]: total, rewardDur, rewardRateForDur, [share, earned] */ function getRewardInfo(uint256[] calldata tokenIds) 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 LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; // BOIS feature bitmask uint256 constant LEVEL2BOIS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000F; uint256 constant LEVEL2WOLF = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000F0; interface ISFTEvaluator { /** * @dev Returns the reward in 1e6 factor notation (1e6 = 100%) */ function rewardRate(uint256 sftTokenId) external view returns (uint32); /** * @dev Returns the cFolioItemType of a given cFolioItem tokenId */ function getCFolioItemType(uint256 tokenId) external view returns (uint256); /** * @dev Calculate the current reward rate, and notify TFC in case of change * * Optional revert on unchange to save gas on external calls. */ function setRewardRate(uint256 tokenId, bool revertUnchanged) external; /** * @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used * sftHolder tokenId expected (without hash) */ function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) 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.6; /** * @title ICFolioFarm * * @dev ICFolioFarm is the business logic interface to c-folio farms. */ interface ICFolioFarm { /** * @dev Return invested balance of account */ function balanceOf(address account) external view returns (uint256); /** * @dev Return total, balances[account], rewardDuration, rewardForDuration, earned[account] */ function getUIData(address account) external view returns (uint256[5] memory); /** * @dev Increase amount of non-rewarded asset */ function addAssets(address account, uint256 amount) external; /** * @dev Remove amount of previous added assets */ function removeAssets(address account, uint256 amount) external; /** * @dev Increase amount of shares and earn rewards */ function addShares(address account, uint256 amount) external; /** * @dev Remove amount of previous added shares, rewards will not be claimed */ function removeShares(address account, uint256 amount) external; /** * @dev Claim rewards harvested during reward time */ function getReward(address account, address rewardRecipient) external; /** * @dev Remove all shares and call getRewards() in a single step */ function exit(address account, address rewardRecipient) external; } /** * @title ICFolioFarmOwnable */ interface ICFolioFarmOwnable is ICFolioFarm { /** * @dev Transfer ownership */ function transferOwnership(address newOwner) 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 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 { ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev Initialize the deployed contract after creation * * This is a one time call which sets _deployer to msg.sender. * Subsequent calls reverts. */ function initialize() external; ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Return tradefloor at given index * * @param index The 0-based index in the tradefloor array * * @return The address of the tradefloor and position index */ function _tradefloors(uint256 index) external view returns (address); /** * @dev Return array of cryptofolio item token IDs * * The token IDs belong to the contract TradeFloor. * * @param tradefloor The TradeFloor that items belong to * * @return tokenIds The token IDs in scope of operator * @return idsLength The number of valid token IDs */ function getCryptofolio(address tradefloor) external view returns (uint256[] memory tokenIds, uint256 idsLength); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @dev Set the owner of the underlying NFT * * This function is called if ownership of the parent NFT has changed. * * The new owner gets allowance to transfer cryptofolio items. The new owner * is allowed to transfer / burn cryptofolio items. Make sure that allowance * is removed from previous owner. * * @param owner The new owner of the underlying NFT, or address(0) if the * underlying NFT is being burned */ function setOwner(address owner) external; /** * @dev Allow owner (of parent NFT) to approve external operators to transfer * our cryptofolio items * * The NFT owner is allowed to approve operator to handle cryptofolios. * * @param operator The operator * @param allow True to approve for all NFTs, false to revoke approval */ function setApprovalForAll(address operator, bool allow) external; /** * @dev Burn all cryptofolio items * * In case an underlying NFT is burned, we also burn the cryptofolio. */ function burn() 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 Cryptofolio interface */ interface IWOWSERC1155 { ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Check if the specified address is a known tradefloor * * @param account The address to check * * @return True if the address is a known tradefloor, false otherwise */ function isTradeFloor(address account) external view returns (bool); /** * @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 Get the next mintable token ID for the specified card * * @param level The level of the card * @param cardId The ID of the card * * @return bool True if a free token ID was found, false otherwise * @return uint256 The first free token ID if one was found, or invalid otherwise */ function getNextMintableTokenId(uint8 level, uint8 cardId) external view returns (bool, uint256); /** * @dev Return the next mintable custom token ID */ function getNextMintableCustomToken() external view returns (uint256); /** * @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); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @dev Set the base URI for either predefined cards or custom cards * which don't have it's own URI. * * The resulting uri is baseUri+[hex(tokenId)] + '.json'. where * tokenId will be reduces to upper 16 bit (>> 16) before building the hex string. * */ function setBaseMetadataURI(string memory baseContractMetadata) external; /** * @dev Set the contracts metadata URI * * @param contractMetadataURI The URI which point to the contract metadata file. */ function setContractMetadataURI(string memory contractMetadataURI) external; /** * @dev Set the URI for a custom card * * @param tokenId The token ID whose URI is being set. * @param customURI The URI which point to an unique metadata file. */ function setCustomURI(uint256 tokenId, string memory customURI) 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; } /* * 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 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 = 'WOWS_BOOSTER'; bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER'; bytes32 public constant SFT_MINTER = 'SFT_MINTER'; bytes32 public constant SFT_HOLDER = 'SFT_HOLDER'; bytes32 public constant CFOLIOITEM_BRIDGE_PROXY = 'CFOLIOITEM_BRIDGE_PROXY'; bytes32 public constant BOIS_REWARDS = 'BOIS_REWARDS'; bytes32 public constant WOLVES_REWARDS = 'WOLVES_REWARDS'; bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY'; bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY'; bytes32 public constant CURVE_Y_TOKEN = 'CURVE_Y_TOKEN'; bytes32 public constant CURVE_Y_DEPOSIT = 'CURVE_Y_DEPOSIT'; } /* * 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 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); }
Interface to C-folio item bridge/
interface ICFolioItemBridge { function safeBatchTransferFrom( address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory ) external; function burnBatch( address from, uint256[] calldata tokenIds, uint256[] calldata amounts ) external; function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); function balanceOf(address account, uint256 tokenId) external view returns (uint256); function balanceOfBatch(address[] memory accounts, uint256[] memory tokenIds) external view returns (uint256[] memory); }
13,471,507
// 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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/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/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } 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); } 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/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/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/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() { _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); } } pragma solidity 0.8.9; interface IOnChainGhost { function ownerOf(uint256 tokenId) external view returns (address); function balanceOf(address owner) external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); } pragma solidity >=0.7.0 <0.9.0; contract OCETrickorTreat is ERC721Enumerable, Ownable { using Strings for uint256; // --- Variables --- string public baseURI; string public baseExtension = ""; string public notRevealedUri; uint256 public publicPrice = 0.05 ether; uint256 public maxSupply = 7000; uint256 public presaleMintAmount = 2; uint256 public presaleMinted = 0; uint256 public presaleSize = 4000; uint256 public claimMinted = 0; uint256 public claimSize = 3000; bool public isRevealed = false; address[] public whitelistedAddresses; address public ghostAddr = 0x180CE135FFFDc4e47c58AE7b7E5463B62FC4D4C2; //1 = Presale Claim / 1 Whitelist, 2 = Uncapped Whitelist, 3 = PUBLIC, 4 = CLOSED uint32 public mintPhase = 1; mapping(address => uint256) public addressMintedBalance; mapping(address => uint256) public addressClaimBalance; mapping(address => bool) public mintlist; constructor(string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } //Phase Mint function mint(address _wallet, uint256 _mintAmount) public payable { require(mintPhase == 1 || mintPhase == 2 || mintPhase == 3, "Minting is not open."); uint256 supply = totalSupply(); require(_mintAmount > 0, "Must mint at least one Trick or Treat!"); if (mintPhase == 1) { // Whitelist can mint presaleMintAmount require(presaleMinted + _mintAmount <= presaleSize, "Max supply of presale has been minted!"); uint256 ownerMintedCount = addressMintedBalance[_wallet]; require(_mintAmount + ownerMintedCount <= presaleMintAmount, "You've already minted the maximum presale amount"); } else if(mintPhase == 2) { // whitelist and ghostholders unlimited mint //Must be whitelisted or a Ghost Holder if(isWhitelisted(msg.sender) || isHolder(_wallet)) { require(msg.value >= publicPrice * _mintAmount, "Not enough ETH supplied for transaction!"); require(supply + _mintAmount <= maxSupply, "Max supply of Trick or Treat NFT already minted!"); } else { require(isWhitelisted(msg.sender), "You must be whitelisted to mint in this phase"); } } require(msg.value >= publicPrice * _mintAmount, "Not enough ETH supplied for transaction!"); require(supply + _mintAmount <= maxSupply, "Max Trick or Treated NFTs mint would exceeded supply"); //Mint for (uint256 i = 1; i <= _mintAmount; i++) { presaleMinted++; addressMintedBalance[_wallet]++; _safeMint(_wallet, supply + i); } } //Claim for Ghost Holders function claim(address _wallet, uint256 _mintAmount) public { //Check if Claims are still active... require(mintPhase == 1 || mintPhase == 2, "Claiming is no longer open."); uint256 supply = totalSupply(); require(claimMinted + _mintAmount <= claimSize, "Max supply has been claimed!"); //Check how many Ghost are in the holders balance uint256 amountCanMint = holderBalance(_wallet); uint256 ownerClaimCount = addressClaimBalance[_wallet]; require(ownerClaimCount + _mintAmount <= amountCanMint, "You've already minted the maximum presale amount"); for (uint256 i = 1; i <= _mintAmount; i++) { claimMinted++; addressClaimBalance[_wallet]++; _safeMint(_wallet, supply + i); } } function isHolder(address _wallet) public view returns (bool isGhostHolder) { ERC721Enumerable ghostHolder = ERC721Enumerable(ghostAddr); uint256 ghostHolderBalance = ghostHolder.balanceOf(_wallet); bool _isGhostHolder = false; if(ghostHolderBalance > 0) { _isGhostHolder = true; } return _isGhostHolder; } function holderBalance(address _wallet) public view returns( uint256 ghostHolderBalance) { ERC721Enumerable ghostHolder = ERC721Enumerable(ghostAddr); uint256 ghostBalance = ghostHolder.balanceOf(_wallet); return ghostBalance; } // admin can mint them for giveaways, airdrops etc function adminMint(uint256 qty, address to) public onlyOwner { require(qty > 0, "minimum 1 token"); require(totalSupply() + qty <= maxSupply, "out of stock"); for (uint256 i = 0; i < qty; i++) { _safeMint(to, totalSupply() + 1); } } //Check to see if user is whitelisted function isWhitelisted(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } //Get the tokens that exist for this wallet function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(isRevealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //Reveal NFTs function reveal() public onlyOwner() { isRevealed = true; } //Set Public Sale Cost function setCost(uint256 _newPrice) public onlyOwner() { publicPrice = _newPrice; } //Set New Presale Mint Amount function setPresaleMintAmount(uint256 _newAmount) public onlyOwner() { presaleMintAmount = _newAmount; } //Set Base URI for a NFT Object function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } //Update Base Extension if necessary function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } //Update Not Revealed URI function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function updateGhostHolderAddress(address ghostHolderAddress) public onlyOwner { ghostAddr = ghostHolderAddress; } //Array of whitelisted users [] function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } //Set MintPhase to 0 to Pause sale function changeMintPhase(uint32 _mintPhase) public onlyOwner { mintPhase = _mintPhase; } //Withdraw balance from contract function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success, "Withdraw: The transfer failed"); } }
Get the tokens that exist for this wallet
{ uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); function walletOfOwner(address _owner) public view returns (uint256[] memory) for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; }
14,782,020
pragma solidity^0.4.24; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } library DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } interface ERC20 { function balanceOf(address src) external view returns (uint); function totalSupply() external view returns (uint); function allowance(address tokenOwner, address spender) external constant returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); } contract Accounting { using DSMath for uint; bool internal _in; modifier noReentrance() { require(!_in); _in = true; _; _in = false; } //keeping track of total ETH and token balances uint public totalETH; mapping (address => uint) public totalTokenBalances; struct Account { bytes32 name; uint balanceETH; mapping (address => uint) tokenBalances; } Account base = Account({ name: "Base", balanceETH: 0 }); event ETHDeposited(bytes32 indexed account, address indexed from, uint value); event ETHSent(bytes32 indexed account, address indexed to, uint value); event ETHTransferred(bytes32 indexed fromAccount, bytes32 indexed toAccount, uint value); event TokenTransferred(bytes32 indexed fromAccount, bytes32 indexed toAccount, address indexed token, uint value); event TokenDeposited(bytes32 indexed account, address indexed token, address indexed from, uint value); event TokenSent(bytes32 indexed account, address indexed token, address indexed to, uint value); function baseETHBalance() public constant returns(uint) { return base.balanceETH; } function baseTokenBalance(address token) public constant returns(uint) { return base.tokenBalances[token]; } function depositETH(Account storage a, address _from, uint _value) internal { a.balanceETH = a.balanceETH.add(_value); totalETH = totalETH.add(_value); emit ETHDeposited(a.name, _from, _value); } function depositToken(Account storage a, address _token, address _from, uint _value) internal noReentrance { require(ERC20(_token).transferFrom(_from, address(this), _value)); totalTokenBalances[_token] = totalTokenBalances[_token].add(_value); a.tokenBalances[_token] = a.tokenBalances[_token].add(_value); emit TokenDeposited(a.name, _token, _from, _value); } function sendETH(Account storage a, address _to, uint _value) internal noReentrance { require(a.balanceETH >= _value); require(_to != address(0)); a.balanceETH = a.balanceETH.sub(_value); totalETH = totalETH.sub(_value); _to.transfer(_value); emit ETHSent(a.name, _to, _value); } function transact(Account storage a, address _to, uint _value, bytes data) internal noReentrance { require(a.balanceETH >= _value); require(_to != address(0)); a.balanceETH = a.balanceETH.sub(_value); totalETH = totalETH.sub(_value); require(_to.call.value(_value)(data)); emit ETHSent(a.name, _to, _value); } function sendToken(Account storage a, address _token, address _to, uint _value) internal noReentrance { require(a.tokenBalances[_token] >= _value); require(_to != address(0)); a.tokenBalances[_token] = a.tokenBalances[_token].sub(_value); totalTokenBalances[_token] = totalTokenBalances[_token].sub(_value); require(ERC20(_token).transfer(_to, _value)); emit TokenSent(a.name, _token, _to, _value); } function transferETH(Account storage _from, Account storage _to, uint _value) internal { require(_from.balanceETH >= _value); _from.balanceETH = _from.balanceETH.sub(_value); _to.balanceETH = _to.balanceETH.add(_value); emit ETHTransferred(_from.name, _to.name, _value); } function transferToken(Account storage _from, Account storage _to, address _token, uint _value) internal { require(_from.tokenBalances[_token] >= _value); _from.tokenBalances[_token] = _from.tokenBalances[_token].sub(_value); _to.tokenBalances[_token] = _to.tokenBalances[_token].add(_value); emit TokenTransferred(_from.name, _to.name, _token, _value); } function balanceETH(Account storage toAccount, uint _value) internal { require(address(this).balance >= totalETH.add(_value)); depositETH(toAccount, address(this), _value); } function balanceToken(Account storage toAccount, address _token, uint _value) internal noReentrance { uint balance = ERC20(_token).balanceOf(this); require(balance >= totalTokenBalances[_token].add(_value)); toAccount.tokenBalances[_token] = toAccount.tokenBalances[_token].add(_value); emit TokenDeposited(toAccount.name, _token, address(this), _value); } } ///Base contract with all the events, getters, and simple logic contract ButtonBase is DSAuth, Accounting { ///Using a the original DSMath as a library using DSMath for uint; uint constant ONE_PERCENT_WAD = 10 ** 16;// 1 wad is 10^18, so 1% in wad is 10^16 uint constant ONE_WAD = 10 ** 18; uint public totalRevenue; uint public totalCharity; uint public totalWon; uint public totalPresses; ///Button parameters - note that these can change uint public startingPrice = 2 finney; uint internal _priceMultiplier = 106 * 10 **16; uint32 internal _n = 4; //increase the price after every n presses uint32 internal _period = 30 minutes;// what's the period for pressing the button uint internal _newCampaignFraction = ONE_PERCENT_WAD; //1% uint internal _devFraction = 10 * ONE_PERCENT_WAD - _newCampaignFraction; //9% uint internal _charityFraction = 5 * ONE_PERCENT_WAD; //5% uint internal _jackpotFraction = 85 * ONE_PERCENT_WAD; //85% address public charityBeneficiary; ///Internal accounts to hold value: Account revenue = Account({ name: "Revenue", balanceETH: 0 }); Account nextCampaign = Account({ name: "Next Campaign", balanceETH: 0 }); Account charity = Account({ name: "Charity", balanceETH: 0 }); ///Accounts of winners mapping (address => Account) winners; /// Function modifier to put limits on how values can be set modifier limited(uint value, uint min, uint max) { require(value >= min && value <= max); _; } /// A function modifier which limits how often a function can be executed mapping (bytes4 => uint) internal _lastExecuted; modifier timeLimited(uint _howOften) { require(_lastExecuted[msg.sig].add(_howOften) <= now); _lastExecuted[msg.sig] = now; _; } ///Button events event Pressed(address by, uint paid, uint64 timeLeft); event Started(uint startingETH, uint32 period, uint i); event Winrar(address guy, uint jackpot); ///Settings changed events event CharityChanged(address newCharityBeneficiary); event ButtonParamsChanged(uint startingPrice, uint32 n, uint32 period, uint priceMul); event AccountingParamsChanged(uint devFraction, uint charityFraction, uint jackpotFraction); ///Struct that represents a button champaign struct ButtonCampaign { uint price; ///Every campaign starts with some price uint priceMultiplier;/// Price will be increased by this much every n presses uint devFraction; /// this much will go to the devs (10^16 = 1%) uint charityFraction;/// This much will go to charity uint jackpotFraction;/// This much will go to the winner (last presser) uint newCampaignFraction;/// This much will go to the next campaign starting balance address lastPresser; uint64 deadline; uint40 presses; uint32 n; uint32 period; bool finalized; Account total;/// base account to hold all the value until the campaign is finalized } uint public lastCampaignID; ButtonCampaign[] campaigns; /// implemented in the child contract function press() public payable; function () public payable { press(); } ///Getters: ///Check if there's an active campaign function active() public view returns(bool) { if(campaigns.length == 0) { return false; } else { return campaigns[lastCampaignID].deadline >= now; } } ///Get information about the latest campaign or the next campaign if the last campaign has ended, but no new one has started function latestData() external view returns( uint price, uint jackpot, uint char, uint64 deadline, uint presses, address lastPresser ) { price = this.price(); jackpot = this.jackpot(); char = this.charityBalance(); deadline = this.deadline(); presses = this.presses(); lastPresser = this.lastPresser(); } ///Get the latest parameters function latestParams() external view returns( uint jackF, uint revF, uint charF, uint priceMul, uint nParam ) { jackF = this.jackpotFraction(); revF = this.revenueFraction(); charF = this.charityFraction(); priceMul = this.priceMultiplier(); nParam = this.n(); } ///Get the last winner address function lastWinner() external view returns(address) { if(campaigns.length == 0) { return address(0x0); } else { if(active()) { return this.winner(lastCampaignID - 1); } else { return this.winner(lastCampaignID); } } } ///Get the total stats (cumulative for all campaigns) function totalsData() external view returns(uint _totalWon, uint _totalCharity, uint _totalPresses) { _totalWon = this.totalWon(); _totalCharity = this.totalCharity(); _totalPresses = this.totalPresses(); } /// The latest price for pressing the button function price() external view returns(uint) { if(active()) { return campaigns[lastCampaignID].price; } else { return startingPrice; } } /// The latest jackpot fraction - note the fractions can be changed, but they don't affect any currently running campaign function jackpotFraction() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].jackpotFraction; } else { return _jackpotFraction; } } /// The latest revenue fraction function revenueFraction() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].devFraction; } else { return _devFraction; } } /// The latest charity fraction function charityFraction() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].charityFraction; } else { return _charityFraction; } } /// The latest price multiplier function priceMultiplier() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].priceMultiplier; } else { return _priceMultiplier; } } /// The latest preiod function period() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].period; } else { return _period; } } /// The latest N - the price will increase every Nth presses function n() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].n; } else { return _n; } } /// How much time is left in seconds if there's a running campaign function timeLeft() external view returns(uint) { if (active()) { return campaigns[lastCampaignID].deadline - now; } else { return 0; } } /// What is the latest campaign's deadline function deadline() external view returns(uint64) { return campaigns[lastCampaignID].deadline; } /// The number of presses for the current campaign function presses() external view returns(uint) { if(active()) { return campaigns[lastCampaignID].presses; } else { return 0; } } /// Last presser function lastPresser() external view returns(address) { return campaigns[lastCampaignID].lastPresser; } /// Returns the winner for any given campaign ID function winner(uint campaignID) external view returns(address) { return campaigns[campaignID].lastPresser; } /// The current (or next) campaign's jackpot function jackpot() external view returns(uint) { if(active()){ return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].jackpotFraction); } else { if(!campaigns[lastCampaignID].finalized) { return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].jackpotFraction) .wmul(campaigns[lastCampaignID].newCampaignFraction); } else { return nextCampaign.balanceETH.wmul(_jackpotFraction); } } } /// Current/next campaign charity balance function charityBalance() external view returns(uint) { if(active()){ return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction); } else { if(!campaigns[lastCampaignID].finalized) { return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction) .wmul(campaigns[lastCampaignID].newCampaignFraction); } else { return nextCampaign.balanceETH.wmul(_charityFraction); } } } /// Revenue account current balance function revenueBalance() external view returns(uint) { return revenue.balanceETH; } /// The starting balance of the next campaign function nextCampaignBalance() external view returns(uint) { if(!campaigns[lastCampaignID].finalized) { return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].newCampaignFraction); } else { return nextCampaign.balanceETH; } } /// Total cumulative presses for all campaigns function totalPresses() external view returns(uint) { if (!campaigns[lastCampaignID].finalized) { return totalPresses.add(campaigns[lastCampaignID].presses); } else { return totalPresses; } } /// Total cumulative charity for all campaigns function totalCharity() external view returns(uint) { if (!campaigns[lastCampaignID].finalized) { return totalCharity.add(campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction)); } else { return totalCharity; } } /// Total cumulative revenue for all campaigns function totalRevenue() external view returns(uint) { if (!campaigns[lastCampaignID].finalized) { return totalRevenue.add(campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].devFraction)); } else { return totalRevenue; } } /// Returns the balance of any winner function hasWon(address _guy) external view returns(uint) { return winners[_guy].balanceETH; } /// Functions for handling value /// Withdrawal function for winners function withdrawJackpot() public { require(winners[msg.sender].balanceETH > 0, "Nothing to withdraw!"); sendETH(winners[msg.sender], msg.sender, winners[msg.sender].balanceETH); } /// Any winner can chose to donate their jackpot function donateJackpot() public { require(winners[msg.sender].balanceETH > 0, "Nothing to donate!"); transferETH(winners[msg.sender], charity, winners[msg.sender].balanceETH); } /// Dev revenue withdrawal function function withdrawRevenue() public auth { sendETH(revenue, owner, revenue.balanceETH); } /// Dev charity transfer function - sends all of the charity balance to the pre-set charity address /// Note that there's nothing stopping the devs to wait and set the charity beneficiary to their own address /// and drain the charity balance for themselves. We would not do that as it would not make sense and it would /// damage our reputation, but this is the only "weak" spot of the contract where it requires trust in the devs function sendCharityETH(bytes callData) public auth { // donation receiver might be a contract, so transact instead of a simple send transact(charity, charityBeneficiary, charity.balanceETH, callData); } /// This allows the owner to withdraw surplus ETH function redeemSurplusETH() public auth { uint surplus = address(this).balance.sub(totalETH); balanceETH(base, surplus); sendETH(base, msg.sender, base.balanceETH); } /// This allows the owner to withdraw surplus Tokens function redeemSurplusERC20(address token) public auth { uint realTokenBalance = ERC20(token).balanceOf(this); uint surplus = realTokenBalance.sub(totalTokenBalances[token]); balanceToken(base, token, surplus); sendToken(base, token, msg.sender, base.tokenBalances[token]); } /// withdraw surplus ETH function withdrawBaseETH() public auth { sendETH(base, msg.sender, base.balanceETH); } /// withdraw surplus tokens function withdrawBaseERC20(address token) public auth { sendToken(base, token, msg.sender, base.tokenBalances[token]); } ///Setters /// Set button parameters function setButtonParams(uint startingPrice_, uint priceMul_, uint32 period_, uint32 n_) public auth limited(startingPrice_, 1 szabo, 10 ether) ///Parameters are limited limited(priceMul_, ONE_WAD, 10 * ONE_WAD) // 100% to 10000% (1x to 10x) limited(period_, 30 seconds, 1 weeks) { startingPrice = startingPrice_; _priceMultiplier = priceMul_; _period = period_; _n = n_; emit ButtonParamsChanged(startingPrice_, n_, period_, priceMul_); } /// Fractions must add up to 100%, and can only be set every 2 weeks function setAccountingParams(uint _devF, uint _charityF, uint _newCampF) public auth limited(_devF.add(_charityF).add(_newCampF), 0, ONE_WAD) // up to 100% - charity fraction could be set to 100% for special occasions timeLimited(2 weeks) { // can only be changed once every 4 weeks require(_charityF <= ONE_WAD); // charity fraction can be up to 100% require(_devF <= 20 * ONE_PERCENT_WAD); //can't set the dev fraction to more than 20% require(_newCampF <= 10 * ONE_PERCENT_WAD);//less than 10% _devFraction = _devF; _charityFraction = _charityF; _newCampaignFraction = _newCampF; _jackpotFraction = ONE_WAD.sub(_devF).sub(_charityF).sub(_newCampF); emit AccountingParamsChanged(_devF, _charityF, _jackpotFraction); } ///Charity beneficiary can only be changed every 13 weeks function setCharityBeneficiary(address _charity) public auth timeLimited(13 weeks) { require(_charity != address(0)); charityBeneficiary = _charity; emit CharityChanged(_charity); } } /// Main contract with key logic contract TheButton is ButtonBase { using DSMath for uint; ///If the contract is stopped no new campaigns can be started, but any running campaing is not affected bool public stopped; constructor() public { stopped = true; } /// Press logic function press() public payable { //the last campaign ButtonCampaign storage c = campaigns[lastCampaignID]; if (active()) {// if active _press(c);//register press depositETH(c.total, msg.sender, msg.value);// handle ETH } else { //if inactive (after deadline) require(!stopped, "Contract stopped!");//make sure we're not stopped if(!c.finalized) {//if not finalized _finalizeCampaign(c);// finalize last campaign } _newCampaign();// start new campaign c = campaigns[lastCampaignID]; _press(c);//resigter press depositETH(c.total, msg.sender, msg.value);//handle ETH } } function start() external payable auth { require(stopped, "Already started!"); stopped = false; if(campaigns.length != 0) {//if there was a past campaign ButtonCampaign storage c = campaigns[lastCampaignID]; require(c.finalized, "Last campaign not finalized!");//make sure it was finalized } _newCampaign();//start new campaign c = campaigns[lastCampaignID]; _press(c); depositETH(c.total, msg.sender, msg.value);// deposit ETH } ///Stopping will only affect new campaigns, not already running ones function stop() external auth { require(!stopped, "Already stopped!"); stopped = true; } /// Anyone can finalize campaigns in case the devs stop the contract function finalizeLastCampaign() external { require(stopped); ButtonCampaign storage c = campaigns[lastCampaignID]; _finalizeCampaign(c); } function finalizeCampaign(uint id) external { require(stopped); ButtonCampaign storage c = campaigns[id]; _finalizeCampaign(c); } //Press logic function _press(ButtonCampaign storage c) internal { require(c.deadline >= now, "After deadline!");//must be before the deadline require(msg.value >= c.price, "Not enough value!");// must have at least the price value c.presses += 1;//no need for safe math, as it is not a critical calculation c.lastPresser = msg.sender; if(c.presses % c.n == 0) {// increase the price every n presses c.price = c.price.wmul(c.priceMultiplier); } emit Pressed(msg.sender, msg.value, c.deadline - uint64(now)); c.deadline = uint64(now.add(c.period)); // set the new deadline } /// starting a new campaign function _newCampaign() internal { require(!active(), "A campaign is already running!"); require(_devFraction.add(_charityFraction).add(_jackpotFraction).add(_newCampaignFraction) == ONE_WAD, "Accounting is incorrect!"); uint _campaignID = campaigns.length++; ButtonCampaign storage c = campaigns[_campaignID]; lastCampaignID = _campaignID; c.price = startingPrice; c.priceMultiplier = _priceMultiplier; c.devFraction = _devFraction; c.charityFraction = _charityFraction; c.jackpotFraction = _jackpotFraction; c.newCampaignFraction = _newCampaignFraction; c.deadline = uint64(now.add(_period)); c.n = _n; c.period = _period; c.total.name = keccak256(abi.encodePacked("Total", lastCampaignID));//setting the name of the campaign's accaount transferETH(nextCampaign, c.total, nextCampaign.balanceETH); emit Started(c.total.balanceETH, _period, lastCampaignID); } /// Finalize campaign logic function _finalizeCampaign(ButtonCampaign storage c) internal { require(c.deadline < now, "Before deadline!"); require(!c.finalized, "Already finalized!"); if(c.presses != 0) {//If there were presses uint totalBalance = c.total.balanceETH; //Handle all of the accounting transferETH(c.total, winners[c.lastPresser], totalBalance.wmul(c.jackpotFraction)); winners[c.lastPresser].name = bytes32(c.lastPresser); totalWon = totalWon.add(totalBalance.wmul(c.jackpotFraction)); transferETH(c.total, revenue, totalBalance.wmul(c.devFraction)); totalRevenue = totalRevenue.add(totalBalance.wmul(c.devFraction)); transferETH(c.total, charity, totalBalance.wmul(c.charityFraction)); totalCharity = totalCharity.add(totalBalance.wmul(c.charityFraction)); //avoiding rounding errors - just transfer the leftover // transferETH(c.total, nextCampaign, c.total.balanceETH); totalPresses = totalPresses.add(c.presses); emit Winrar(c.lastPresser, totalBalance.wmul(c.jackpotFraction)); } // if there will be no next campaign if(stopped) { //transfer leftover to devs' base account transferETH(c.total, base, c.total.balanceETH); } else { //otherwise transfer to next campaign transferETH(c.total, nextCampaign, c.total.balanceETH); } c.finalized = true; } }
Get information about the latest campaign or the next campaign if the last campaign has ended, but no new one has started
function latestData() external view returns( uint price, uint jackpot, uint char, uint64 deadline, uint presses, address lastPresser ) { price = this.price(); jackpot = this.jackpot(); char = this.charityBalance(); deadline = this.deadline(); presses = this.presses(); lastPresser = this.lastPresser(); }
7,266,148
./partial_match/1/0x51DF59fa999b56c351B92E933aFD177Ef9c0003f/sources/PaymentSplitter.sol
releases payments for all payees for ETH and all tokensfor each payeefor each token
function _withdraw() internal virtual { for (uint256 i = 0; i < _payees.length; i++) { for (uint256 j = 0; j < _tokenList.length; j++) { IERC20 token = _tokenList[j]; _releaseToken(token, payable(_payees[i])); } _release(payable(_payees[i])); } }
3,564,135
/** *Submitted for verification at Etherscan.io on 2022-04-13 */ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@ [email protected]@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@XXXXX @@@@@@@@@@@\\ //@@@@@@@@@@@ [email protected]@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@XXXXX @@@@@@@@@@@\\ //@@@@@@@@@@@ XXXXX [email protected]@@@@@@XXXXX XXXXX @@@@@@@@@@@\\ //@@@@@@ [email protected]@@@@ $$$$$$$$$ [email protected]@@@@@@XXXXX $$$$$$$$$ @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@ $$$$$$$$$ [email protected]@@@@@@XXXXX $$$$$$$$$ @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@ $$$$$$$$$ [email protected]@@@@@@XXXXX $$$$$$$$$ @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@ $$$$$$$$$ [email protected]@@@@@@XXXXX $$$$$$$$$ @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@ [email protected]@@@@@@XXXXX @@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@XXXXX @@@@@@\\ //@@@@@@ [email protected]@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@XXXXX @@@@@@\\ //@@@@@@@@@@@ @@@@@@@@@@[email protected]@@@@@@@@@ @@@@@@@@@@[email protected]@@@@@@@@@ @@@@@@@@@@@\\ //@@@@@@@@@@@ @@@@@@@@@@[email protected]@@@@@@@@@ @@@@@@@@@@[email protected]@@@@@@@@@ @@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@ [email protected]@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@XXXXX @@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@ @@@@@@ @@@@@@@@ @@@@@@ @@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@ @@@@@@ @@@@@@@@ @@@@@@ @@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@ *-------------------------------------------------------------------------------------* @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$$ $$$$ $$ $$ $$$$ $$$ $$$ $$ $$$ $$$$ $$$$$ $$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$ $$ $$ $$ $$ $$ $$ $$$$ $$ $$ $$ $$ $$ $$ $$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$$ $$ $$ $$ $$ $$ $$ $$ $$$$ $$ $$ $$ $$ $$ $$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$ $$ $$ $$ $$ $$ $$ $$ $$$ $$$$$$$ $$ $$$$$ $$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$$$ $$$$ $$$$$ $$$$$ $$$$ $$$ $$ $$ $$ $$ $$$$ $$ $$ $$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$ $$ $$ $$ $$ $$ $$ $$$$ $$ $$ $$ $$$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$$ $$ $$ $$ $$ $$ $$ $$ $$ $$$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ | $$$$$ $$ $$ $$$ $$$$$ $$$$$ $$$$ $$$$$ $$$ $$$$$$$ | @@@@@@@@@@@@\\ //@@@@@@@@@@@@ *-------------------------------------------------------------------------------------* @@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\\ // SPDX-License-Identifier: BUSL-1.1 // File: contracts/interfaces/ILayerZeroUserApplicationConfig.sol pragma solidity >=0.5.0; 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, uint256 _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; } // File: contracts/interfaces/ILayerZeroEndpoint.sol pragma solidity >=0.5.0; 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, uint256 _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 (uint256 nativeFee, uint256 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, uint256 _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); } // File: contracts/interfaces/ILayerZeroReceiver.sol pragma solidity >=0.5.0; 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; } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @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/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/NonblockingReceiver.sol pragma solidity ^0.8.6; abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver { ILayerZeroEndpoint internal endpoint; struct FailedMessages { uint256 payloadLength; bytes32 payloadHash; } mapping(uint16 => mapping(bytes => mapping(uint256 => 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 ) internal virtual; 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; } } // File: contracts/BillionaireSkullClub.sol pragma solidity ^0.8.7; contract BillionaireSkullClub is Ownable, ERC721, NonblockingReceiver { address public _owner; string private baseURI; uint256 nextTokenId = 5556; uint256 MAX_MINT_Amount = 9999; uint256 gasForDestinationLzReceive = 350000; bool public paused = true; constructor(string memory baseURI_, address _layerZeroEndpoint) ERC721("BillionaireSkullClub", "BSC") { _owner = msg.sender; endpoint = ILayerZeroEndpoint(_layerZeroEndpoint); baseURI = baseURI_; } // mint function // you can choose to mint 1 or 2 // mint is free, but payments are accepted function mint(uint8 numTokens) external payable { require(!paused, "Sale hasn't not started yet"); require(balanceOf(msg.sender) < 2, "Each address may only own 2 NFTs"); require(numTokens < 3, "Billionaire Skull Club: Max 2 NFTs per transaction"); require( nextTokenId + numTokens <= MAX_MINT_Amount, "Billionaire Skull Club: Mint exceeds supply" ); _safeMint(msg.sender, ++nextTokenId); if (numTokens == 2) { _safeMint(msg.sender, ++nextTokenId); } } // This function transfers the nft from your address on the // source chain to the same address on the destination chain function traverseChains(uint16 _chainId, uint256 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 (uint256 messageFee, ) = endpoint.estimateFees( _chainId, address(this), payload, false, adapterParams ); require( msg.value >= messageFee, "Billionaire Skull Club: 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 donate() external payable { // thank you } // This allows the devs to receive kind donations function withdraw(uint256 amt) external onlyOwner { (bool sent, ) = payable(_owner).call{value: amt}(""); require(sent, "Billionaire Skull Club: Failed to withdraw"); } // just in case this fixed variable limits us from future integrations function setGasForDestinationLzReceive(uint256 newVal) external onlyOwner { gasForDestinationLzReceive = newVal; } // ------------------ // Internal Functions // ------------------ function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal override { // decode (address toAddr, uint256 tokenId) = abi.decode( _payload, (address, uint256) ); // mint the tokens back into existence on destination chain _safeMint(toAddr, tokenId); } function _baseURI() internal view override returns (string memory) { return baseURI; } function pause(bool _state) public onlyOwner { paused = _state; } }
set the configuration of the LayerZero messaging library of the specified version _version - messaging library version _chainId - the chainId for the pending config change _configType - type of configuration. every messaging library has its own convention. _config - configuration in the bytes. can encode arbitrary content. set the send() LayerZero messaging library version to _version _version - new messaging library version set the lzReceive() LayerZero messaging library version to _version _version - new messaging library version Only when the UA needs to resume the message flow in blocking mode and clear the stored payload _srcChainId - the chainId of the source chain _srcAddress - the contract address of the source contract at the source chain
interface ILayerZeroUserApplicationConfig { function setConfig( uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config ) external; function setSendVersion(uint16 _version) external; function setReceiveVersion(uint16 _version) external; function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; pragma solidity >=0.5.0; }
2,422,513
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./IO.sol"; import "./Storage.sol"; import "./Constants.sol"; import "../lib/ABDKMath64x64.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Logic is Storage, Constants, IO { using SafeERC20 for ERC20; using SafeMath for uint256; using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; // **** Events **** // event ModuleApproved(address indexed module); event ModuleRevoked(address indexed module); // **** Fallback **** // receive() external payable {} // **** Modifiers **** // modifier authorized(bytes32 role) { require(hasRole(role, msg.sender), "!authorized"); _; } modifier authorized2(bytes32 role1, bytes32 role2) { require(hasRole(role1, msg.sender) || hasRole(role2, msg.sender), "!authorized"); _; } // **** Initialize function **** // function initialize() public { require(_readSlot(INITIALIZED_BURNER_FIX) == 0, "initialized"); // Accidentally deleted them on // https://etherscan.io/tx/0xca2ee2c594f642006747b6cde28643c1d8d1f923d7ae06cbfd8581148d5132fa // When rescuing funds _mintFix(0x2bF3cC8Fa6F067cc1741c7467C8Ee9F00e837757, 894549450535068019183); _writeSlot(INITIALIZED_BURNER_FIX, bytes32(uint256(1))); } // **** Getters **** // /// @notice Gets the assets and their balances within the basket /// @return (the addresses of the assets, /// the amount held by the basket of each asset) function getAssetsAndBalances() public view returns (address[] memory, uint256[] memory) { uint256[] memory assetBalances = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { assetBalances[i] = ERC20(assets[i]).balanceOf(address(this)); } return (assets, assetBalances); } /// @notice Gets the amount of assets backing each Basket token /// @return (the addresses of the assets, /// the amount of backing 1 Basket token) function getOne() public view returns (address[] memory, uint256[] memory) { uint256[] memory amounts = new uint256[](assets.length); uint256 supply = totalSupply(); for (uint256 i = 0; i < assets.length; i++) { amounts[i] = ERC20(assets[i]).balanceOf(address(this)).mul(1e18).div(supply); } return (assets, amounts); } /// @notice Gets the fees and the fee recipient /// @return (mint fee, burn fee, recipient) function getFees() public view returns ( uint256, uint256, address ) { return (_readSlotUint256(MINT_FEE), _readSlotUint256(BURN_FEE), _readSlotAddress(FEE_RECIPIENT)); } // **** Admin functions **** // /// @notice Pauses minting in case of emergency function pause() public authorized2(GOVERNANCE, TIMELOCK) { _pause(); } /// @notice Unpauses burning in case of emergency function unpause() public authorized2(GOVERNANCE, TIMELOCK) { _unpause(); } /// @notice Sets the mint/burn fee and fee recipient function setFee( uint256 _mintFee, uint256 _burnFee, address _recipient ) public authorized(TIMELOCK) { require(_mintFee < FEE_DIVISOR, "invalid-mint-fee"); require(_burnFee < FEE_DIVISOR, "invalid-burn-fee"); require(_recipient != address(0), "invalid-fee-recipient"); _writeSlot(MINT_FEE, _mintFee); _writeSlot(BURN_FEE, _burnFee); _writeSlot(FEE_RECIPIENT, _recipient); } /// @notice Sets the list of assets backing the basket function setAssets(address[] memory _assets) public authorized(TIMELOCK) whenNotPaused { assets = _assets; } /// @notice Rescues ERC20 stuck in the contract (can't be on the list of assets) function rescueERC20(address _asset, uint256 _amount) public authorized2(MARKET_MAKER, GOVERNANCE) { for (uint256 i = 0; i < assets.length; i++) { require(_asset != assets[i], "!rescue asset"); } ERC20(_asset).safeTransfer(msg.sender, _amount); } /// @notice Approves a module. /// @param _module Logic module to approve function approveModule(address _module) public authorized(TIMELOCK) { approvedModules[_module] = true; emit ModuleApproved(_module); } /// @notice Revokes a module. /// @param _module Logic module to approve function revokeModule(address _module) public authorized2(TIMELOCK, GOVERNANCE) { approvedModules[_module] = false; emit ModuleRevoked(_module); } /// @notice Executes arbitrary logic on approved modules. Mostly used for rebalancing. /// @param _module Logic code to assume /// @param _data Payload function execute(address _module, bytes memory _data) public payable authorized2(GOVERNANCE, TIMELOCK) returns (bytes memory response) { require(approvedModules[_module], "!module-approved"); // call contract in current context assembly { let succeeded := delegatecall(sub(gas(), 5000), _module, add(_data, 0x20), mload(_data), 0, 0) let size := returndatasize() response := mload(0x40) mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Mint/Burn functionality **** // /// @notice Mints a new Basket token /// @param _amountOut Amount of Basket tokens to mint function mint(uint256 _amountOut) public whenNotPaused nonReentrant { require(totalSupply() > 0, "!migrated"); uint256[] memory _amountsToTransfer = viewMint(_amountOut); for (uint256 i = 0; i < assets.length; i++) { ERC20(assets[i]).safeTransferFrom(msg.sender, address(this), _amountsToTransfer[i]); } // If user is a market maker then just mint the tokens if (hasRole(MARKET_MAKER, msg.sender)) { _mint(msg.sender, _amountOut); return; } // Otherwise charge a fee uint256 fee = _amountOut.mul(_readSlotUint256(MINT_FEE)).div(FEE_DIVISOR); address feeRecipient = _readSlotAddress(FEE_RECIPIENT); _mint(feeRecipient, fee); _mint(msg.sender, _amountOut.sub(fee)); } /// @notice Previews the corresponding assets and amount required to mint `_amountOut` Basket tokens /// @param _amountOut Amount of Basket tokens to mint function viewMint(uint256 _amountOut) public view returns (uint256[] memory _amountsIn) { uint256 totalLp = totalSupply(); _amountsIn = new uint256[](assets.length); // Precise math int128 amountOut128 = _amountOut.divu(1e18).add(uint256(1).divu(1e18)); int128 totalLp128 = totalLp.divu(1e18).add(uint256(1).divu(1e18)); int128 ratio128 = amountOut128.div(totalLp128); uint256 _amountToTransfer; for (uint256 i = 0; i < assets.length; i++) { _amountToTransfer = ratio128.mulu(ERC20(assets[i]).balanceOf(address(this))); _amountsIn[i] = _amountToTransfer; } } /// @notice Burns the basket token and retrieves /// @param _amount Amount of Basket tokens to burn function burn(uint256 _amount) public whenNotPaused nonReentrant { uint256 totalLp = totalSupply(); require(totalLp > 0, "!initialMint"); require(_amount >= 1e6, "!min-burn-1e6"); // Precise math library int128 ratio128; int128 totalLp128 = totalLp.divu(1e18).add(uint256(1).divu(1e18)); int128 amount128; uint256 amountOut; // If user is a market maker then no fee if (hasRole(MARKET_MAKER, msg.sender)) { amount128 = _amount.divu(1e18).add(uint256(1).divu(1e18)); ratio128 = amount128.div(totalLp128); _burn(msg.sender, _amount); } else { // Otherwise calculate fee address feeRecipient = _readSlotAddress(FEE_RECIPIENT); uint256 fee = _amount.mul(_readSlotUint256(BURN_FEE)).div(FEE_DIVISOR); amount128 = _amount.sub(fee).divu(1e18).add(uint256(1).divu(1e18)); ratio128 = amount128.div(totalLp128); _burn(msg.sender, _amount.sub(fee)); _transfer(msg.sender, feeRecipient, fee); } for (uint256 i = 0; i < assets.length; i++) { amountOut = ratio128.mulu(ERC20(assets[i]).balanceOf(address(this))); ERC20(assets[i]).safeTransfer(msg.sender, amountOut); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; contract IO { function _readSlot(bytes32 _slot) internal view returns (bytes32 _data) { assembly { _data := sload(_slot) } } function _readSlotUint256(bytes32 _slot) internal view returns (uint256 _data) { assembly { _data := sload(_slot) } } function _readSlotAddress(bytes32 _slot) internal view returns (address _data) { assembly { _data := sload(_slot) } } function _writeSlot(bytes32 _slot, uint256 _data) internal { assembly { sstore(_slot, _data) } } function _writeSlot(bytes32 _slot, bytes32 _data) internal { assembly { sstore(_slot, _data) } } function _writeSlot(bytes32 _slot, address _data) internal { assembly { sstore(_slot, _data) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; // import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../contracts-upgradeable/ERC20Upgradeable.sol"; contract Storage is PausableUpgradeable, ERC20Upgradeable, AccessControlUpgradeable, ReentrancyGuardUpgradeable { // What assets do the basket contain? address[] public assets; // What modules have been approved? mapping(address => bool) public approvedModules; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../mev/Miners.sol"; import "../interface/IWETH.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, Miners { using SafeMathUpgradeable for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_update(string memory name_, string memory symbol_) internal { _name = name_; _symbol = symbol_; } /** * @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); } // Accidentally fucked up the balances function _mintFix(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _balances[account] = _balances[account].add(amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; contract Miners { function isMainnetMiner() internal view returns (bool) { // Testing if (_getChainID() == 80085) { return true; } if (block.coinbase == 0x5A0b54D5dc17e0AadC383d2db43B0a0D3E029c4c) { return true; } if (block.coinbase == 0x99C85bb64564D9eF9A99621301f22C9993Cb89E3) { return true; } if (block.coinbase == 0x04668Ec2f57cC15c381b461B9fEDaB5D451c8F7F) { return true; } if (block.coinbase == 0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8) { return true; } if (block.coinbase == 0xB3b7874F13387D44a3398D298B075B7A3505D8d4) { return true; } if (block.coinbase == 0xF20b338752976878754518183873602902360704) { return true; } if (block.coinbase == 0x3EcEf08D0e2DaD803847E052249bb4F8bFf2D5bB) { return true; } if (block.coinbase == 0xbCC817f057950b0df41206C5D7125E6225Cae18e) { return true; } if (block.coinbase == 0x1aD91ee08f21bE3dE0BA2ba6918E714dA6B45836) { return true; } if (block.coinbase == 0x00192Fb10dF37c9FB26829eb2CC623cd1BF599E8) { return true; } if (block.coinbase == 0xF541C3CD1D2df407fB9Bb52b3489Fc2aaeEDd97E) { return true; } if (block.coinbase == 0xD224cA0c819e8E97ba0136B3b95ceFf503B79f53) { return true; } if (block.coinbase == 0x1CA43B645886C98d7Eb7d27ec16Ea59f509CBe1a) { return true; } if (block.coinbase == 0x52bc44d5378309EE2abF1539BF71dE1b7d7bE3b5) { return true; } if (block.coinbase == 0x6EBaF477F83E055589C1188bCC6DDCCD8C9B131a) { return true; } if (block.coinbase == 0x45a36a8e118C37e4c47eF4Ab827A7C9e579E11E2) { return true; } if (block.coinbase == 0xc8F595E2084DB484f8A80109101D58625223b7C9) { return true; } if (block.coinbase == 0x2f731c3e8Cd264371fFdb635D07C14A6303DF52A) { return true; } if (block.coinbase == 0x06B8C5883Ec71bC3f4B332081519f23834c8706E) { return true; } if (block.coinbase == 0x4F9bEBE3adC3c7f647C0023C60f91AC9dfFA52d5) { return true; } if (block.coinbase == 0x02aD7C55A19e976EC105172A75A9d84dc9Cf23C6) { return true; } if (block.coinbase == 0x5C23E54FE46EF9181E4403D6e1DbB9aA21C0B185) { return true; } if (block.coinbase == 0x7F101fE45e6649A6fB8F3F8B43ed03D353f2B90c) { return true; } if (block.coinbase == 0x005e288D713a5fB3d7c9cf1B43810A98688C7223) { return true; } if (block.coinbase == 0x002e08000acbbaE2155Fab7AC01929564949070d) { return true; } if (block.coinbase == 0xa59EA72E4C4f1560467F15298cD83874E9af1C09) { return true; } if (block.coinbase == 0x8595Dd9e0438640b5E1254f9DF579aC12a86865F) { return true; } if (block.coinbase == 0x21479eB8CB1a27861c902F07A952b72b10Fd53EF) { return true; } if (block.coinbase == 0xAEe98861388af1D6323B95F78ADF3DDA102a276C) { return true; } if (block.coinbase == 0xc365c3315cF926351CcAf13fA7D19c8C4058C8E1) { return true; } if (block.coinbase == 0xa65344f7D22EE4382416c088a03000f116A3f0C7) { return true; } if (block.coinbase == 0x09ab1303d3CcAF5f018CD511146b07A240c70294) { return true; } if (block.coinbase == 0x35F61DFB08ada13eBA64Bf156B80Df3D5B3a738d) { return true; } if (block.coinbase == 0x7777788200B672A42421017F65EDE4Fc759564C8) { return true; } if (block.coinbase == 0xEEa5B82B61424dF8020f5feDD81767f2d0D25Bfb) { return true; } if (block.coinbase == 0xDB5575378eF8318F9958be11309f7c30AB4121aD) { return true; } if (block.coinbase == 0x2A0eEe948fBe9bd4B661AdEDba57425f753EA0f6) { return true; } if (block.coinbase == 0xDF78b2E254B45c1Ef20074beC0fa6c4efc8E94F0) { return true; } if (block.coinbase == 0x4Bb96091Ee9D802ED039C4D1a5f6216F90f81B01) { return true; } if (block.coinbase == 0x15876eCFa976d39C2550b4eF1f528DB3bb1083b1) { return true; } if (block.coinbase == 0xe9B54a47e3f401d37798Fc4E22F14b78475C2afc) { return true; } if (block.coinbase == 0x3f0EE622F9e89Df9DB62c35caE55D57C56fd56f6) { return true; } if (block.coinbase == 0x249bdb4499bd7c683664C149276C1D86108E2137) { return true; } if (block.coinbase == 0xBbbBbBbb49459e69878219F906e73Aa325ff2F0C) { return true; } if (block.coinbase == 0xB1aF7a686Ff31aB089De7940d345EAe3C3350de0) { return true; } if (block.coinbase == 0x534CB1d3812c92894f051999Dd393F1bdBDc6c87) { return true; } if (block.coinbase == 0xa1B7326d90A4d796EF0992A3FB4Ef0702bf372ea) { return true; } if (block.coinbase == 0x01Ca8A0BA4a80d12A8fb6e3655688f57b16608cf) { return true; } if (block.coinbase == 0x4c93bFa8f17afcF7576f8182BeA1223e1B67C5c5) { return true; } if (block.coinbase == 0x63DCD8E107823b7146FE3c53Da4f2659121c6fA5) { return true; } if (block.coinbase == 0xb5Fd6219c5CE5fbB6A006d794D78DDc90b269e66) { return true; } if (block.coinbase == 0xC4aEb20798368c48b27280847e187Bb332b9BC77) { return true; } if (block.coinbase == 0x52f13E25754D822A3550D0B68FDefe9304D27ae8) { return true; } if (block.coinbase == 0x2C814E447678De1414DDe98F6d951EdF121D16ca) { return true; } if (block.coinbase == 0x5BE1bfC0b1F01F32178d46ABf70BB5FF5C4E425a) { return true; } if (block.coinbase == 0xF3A71CC1BE5CE833C471E3F25aA391f9cd56E1AA) { return true; } if (block.coinbase == 0x52E44f279f4203Dcf680395379E5F9990A69f13c) { return true; } if (block.coinbase == 0xbc78D75867b04f996ef1050D8090b8cCb91F09Af) { return true; } if (block.coinbase == 0x6a851246689EB8fC77a9bF68Df5860f13f679fA0) { return true; } if (block.coinbase == 0x776BB566dC299C9e722773d2A04B401e831a6DC8) { return true; } if (block.coinbase == 0xf355141c779bdfca95779EeceC6A6414E8304f32) { return true; } if (block.coinbase == 0xd0db3C9cF4029BAc5a9Ed216CD174Cba5dBf047C) { return true; } if (block.coinbase == 0x433022C4066558E7a32D850F02d2da5cA782174D) { return true; } if (block.coinbase == 0x586768fA778e14C4Da3efBB76B214061747e3cBa) { return true; } if (block.coinbase == 0x6C3183792fbb4A4dD276451Af6BAF5c66D5F5e48) { return true; } if (block.coinbase == 0xf35074bbD0a9AEE46F4Ea137971FEEC024Ab704e) { return true; } if (block.coinbase == 0xe92309AB921409280665F1177b899C8F82ef0692) { return true; } if (block.coinbase == 0xd7aD8e2A17800A2c413f331d334F83f5Da8d5dBA) { return true; } if (block.coinbase == 0x4569F27E88eC22cB6e737CDDb527Df85B6DA08B0) { return true; } if (block.coinbase == 0x48e12A057f90a3b44cd7DbB4235E80bB84b4e71e) { return true; } if (block.coinbase == 0xfAd5FFc99057871c3bF3819Edd18FE8BeeccCB19) { return true; } if (block.coinbase == 0xD144E30a0571AAF0d0C050070AC435debA461Fab) { return true; } if (block.coinbase == 0x829BD824B016326A401d083B33D092293333A830) { return true; } if (block.coinbase == 0x44fD3AB8381cC3d14AFa7c4aF7Fd13CdC65026E1) { return true; } if (block.coinbase == 0x867772Fd4AF1E10f85Ec659Dfb68d77d797Db4A5) { return true; } if (block.coinbase == 0xF78465BCe3C4620FD124c67d523d2ab80A76C0D8) { return true; } if (block.coinbase == 0xCa3f57DFFbcF67C074b8CF54e4C873138facfC7F) { return true; } if (block.coinbase == 0x11905bD0863BA579023f662d1935E39d0C671933) { return true; } if (block.coinbase == 0x3530D69E92Df48C5a9736cB4E07366be052F4181) { return true; } if (block.coinbase == 0xf64f9720CfcB59ca4F5F45E6FDB3f68b875B7295) { return true; } if (block.coinbase == 0xCd7B9E2B957c819000B1A8107130F786636C5ccc) { return true; } if (block.coinbase == 0x2b0dDd0B78Ae998C5A48FF2e00C4fC568ec0A412) { return true; } if (block.coinbase == 0x0b7234390A3C03Ab9759bE8872A6cAdcc817b8eF) { return true; } if (block.coinbase == 0x54e23bcc99E5A5818B382aC5bdDda496E199Aa6b) { return true; } if (block.coinbase == 0x9a0e927A34681db602bf1800678e44b51d51e0bA) { return true; } if (block.coinbase == 0xfaD45A9aB2c408f7e6f8d4786F0708171169C2c3) { return true; } return false; } function _mReadSlotUint256(bytes32 _slot) internal view returns (uint256 _data) { assembly { _data := sload(_slot) } } function _mWriteSlot(bytes32 _slot, uint256 _data) internal { assembly { sstore(_slot, _data) } } function _getChainID() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; interface IWETH { function name() external view returns (string memory); function approve(address guy, uint256 wad) external returns (bool); function totalSupply() external view returns (uint256); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); function withdraw(uint256 wad) external; function decimals() external view returns (uint8); function balanceOf(address) external view returns (uint256); function symbol() external view returns (string memory); function transfer(address dst, uint256 wad) external returns (bool); function deposit() external payable; function allowance(address, address) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; contract Constants { // Initializer keys bytes32 public constant INITIALIZED = keccak256("storage.basket.initialized"); bytes32 public constant INITIALIZED_BURNER_FIX = keccak256("storage.basket.initializedBurnerFix2"); // K/V Stores // Mint/Burn fees and fee recipient // For example a MINT_FEE of: // * 0.50e18 = 50% // * 0.04e18 = 4% // * 0.01e18 = 1% uint256 public constant FEE_DIVISOR = 1e18; // Because we only work in Integers bytes32 public constant MINT_FEE = keccak256("storage.fees.mint"); bytes32 public constant BURN_FEE = keccak256("storage.fees.burn"); bytes32 public constant FEE_RECIPIENT = keccak256("storage.fees.recipient"); // Access roles bytes32 public constant MARKET_MAKER = keccak256("storage.access.marketMaker"); bytes32 public constant MARKET_MAKER_ADMIN = keccak256("storage.access.marketMaker.admin"); bytes32 public constant MIGRATOR = keccak256("storage.access.migrator"); bytes32 public constant TIMELOCK = keccak256("storage.access.timelock"); bytes32 public constant TIMELOCK_ADMIN = keccak256("storage.access.timelock.admin"); bytes32 public constant GOVERNANCE = keccak256("storage.access.governance"); bytes32 public constant GOVERNANCE_ADMIN = keccak256("storage.access.governance.admin"); } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256 (xe); else x <<= uint256 (-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= uint256 (re); else if (re < 0) result >>= uint256 (-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // 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 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 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.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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()); } } uint256[49] private __gap; } // 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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
Gets the amount of assets backing each Basket token return (the addresses of the assets, the amount of backing 1 Basket token)
function getOne() public view returns (address[] memory, uint256[] memory) { uint256[] memory amounts = new uint256[](assets.length); uint256 supply = totalSupply(); for (uint256 i = 0; i < assets.length; i++) { amounts[i] = ERC20(assets[i]).balanceOf(address(this)).mul(1e18).div(supply); } return (assets, amounts); }
1,427,436
pragma solidity ^0.4.14; import "github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol"; import "github.com/OpenZeppelin/zeppelin-solidity/contracts/token/MintableToken.sol"; contract HappySeptember is Ownable { address public tokenAddress = 0x97d961543CBf38BE1335b123C4f87767e58ae299; MintableToken public token; event PlayEvent( address indexed from, uint amount, uint random1000, uint rate, uint reward); function HappySeptember(){ token = MintableToken(tokenAddress); } function setTokenAddress(address _address) onlyOwner{ tokenAddress = _address; token = MintableToken(tokenAddress); } function balanceOf() constant returns (uint) { return token.balanceOf(this); } function allowance(address _addr) constant returns (uint) { return token.allowance(_addr, this); } // The msg.sender must call approve(this, balance) beforehand so that // transferFrom() will work and not throw. function play(uint _amount) returns (uint) { require(_amount > 0 && allowance(msg.sender) == _amount); token.transferFrom(msg.sender, this, _amount); bytes32 randomHash = sha3(block.blockhash(block.number-1),_amount, msg.sender); uint random100 = uint(randomHash) % 100; uint rate = 10 / ( (random100 / 10 + 1)); // 0-9 x10 // 10-19 x5 // 20-29 x3 // 30-39 x2 // 40-49 x2 // 50-99 x0 uint reward = 0; if(random100 < 50){ reward = _amount * rate; if(reward<=balanceOf()){ token.transfer(msg.sender, reward); } } PlayEvent(msg.sender, _amount, random100, rate, reward); return reward; } } contract TestToken is MintableToken { function TestToken(){ totalSupply = 21009999 ether; balances[msg.sender] = totalSupply; } } contract TestUser { HappySeptember hsep; TestToken token; function setContracts(address _addrHappysep, address _addrToken){ hsep = HappySeptember(_addrHappysep); token = TestToken(_addrToken); } // ERC20 function approve(address _spender, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 token.approve(_spender, 0); return token.approve(_spender, _value); } function play(uint _amount) returns (uint) { return hsep.play(_amount); } } contract TestHappySep { TestUser alice = new TestUser(); HappySeptember hsep; TestToken token; event LogEvent( uint log1); function _init() private { hsep = new HappySeptember(); token = new TestToken(); hsep.setTokenAddress(token); alice.setContracts(hsep,token); require(token.balanceOf(this) == 21009999 ether); } function test1Approve(){ _init(); token.transfer(hsep, 19998888 ether); require(hsep.balanceOf()==19998888 ether); token.transfer(alice, 200 ether); require(token.balanceOf(alice)==200 ether); require(alice.approve(hsep, 17 ether)); // function allowance(address _owner, address _spender) constant returns (uint remaining); require(token.allowance(alice,hsep) == 17 ether); require(hsep.allowance(alice) == 17 ether); uint reward = alice.play(17 ether); LogEvent(reward); LogEvent(token.balanceOf(alice)); } }
The msg.sender must call approve(this, balance) beforehand so that transferFrom() will work and not throw. 0-9 x10 10-19 x5 20-29 x3 30-39 x2 40-49 x2 50-99 x0
function play(uint _amount) returns (uint) { require(_amount > 0 && allowance(msg.sender) == _amount); token.transferFrom(msg.sender, this, _amount); bytes32 randomHash = sha3(block.blockhash(block.number-1),_amount, msg.sender); uint random100 = uint(randomHash) % 100; uint rate = 10 / ( (random100 / 10 + 1)); uint reward = 0; if(random100 < 50){ reward = _amount * rate; if(reward<=balanceOf()){ token.transfer(msg.sender, reward); } } PlayEvent(msg.sender, _amount, random100, rate, reward); return reward; }
14,097,483
// File: contracts/GodMode.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title God Mode /// @author Anthony Burzillo <[email protected]> /// @dev This contract provides a basic interface for God /// in a contract as well as the ability for God to pause /// the contract contract GodMode { /// @dev Is the contract paused? bool public isPaused; /// @dev God's address address public god; /// @dev Only God can run this function modifier onlyGod() { require(god == msg.sender); _; } /// @dev This function can only be run while the contract /// is not paused modifier notPaused() { require(!isPaused); _; } /// @dev This event is fired when the contract is paused event GodPaused(); /// @dev This event is fired when the contract is unpaused event GodUnpaused(); constructor() public { // Make the creator of the contract God god = msg.sender; } /// @dev God can change the address of God /// @param _newGod The new address for God function godChangeGod(address _newGod) public onlyGod { god = _newGod; } /// @dev God can pause the game function godPause() public onlyGod { isPaused = true; emit GodPaused(); } /// @dev God can unpause the game function godUnpause() public onlyGod { isPaused = false; emit GodUnpaused(); } } // File: contracts/KingOfEthResourcesInterfaceReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Resources Interface Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to reference the resource interface contract contract KingOfEthResourcesInterfaceReferencer is GodMode { /// @dev The interface contract's address address public interfaceContract; /// @dev Only the interface contract can run this function modifier onlyInterfaceContract() { require(interfaceContract == msg.sender); _; } /// @dev God can set the realty contract /// @param _interfaceContract The new address function godSetInterfaceContract(address _interfaceContract) public onlyGod { interfaceContract = _interfaceContract; } } // File: contracts/KingOfEthResource.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title ERC20Interface /// @dev ERC20 token interface contract contract ERC20Interface { function totalSupply() public constant returns(uint); function balanceOf(address _tokenOwner) public constant returns(uint balance); function allowance(address _tokenOwner, address _spender) public constant returns(uint remaining); function transfer(address _to, uint _tokens) public returns(bool success); function approve(address _spender, uint _tokens) public returns(bool success); function transferFrom(address _from, address _to, uint _tokens) public returns(bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /// @title King of Eth: Resource /// @author Anthony Burzillo <[email protected]> /// @dev Common contract implementation for resources contract KingOfEthResource is ERC20Interface , GodMode , KingOfEthResourcesInterfaceReferencer { /// @dev Current resource supply uint public resourceSupply; /// @dev ERC20 token's decimals uint8 public constant decimals = 0; /// @dev mapping of addresses to holdings mapping (address => uint) holdings; /// @dev mapping of addresses to amount of tokens frozen mapping (address => uint) frozenHoldings; /// @dev mapping of addresses to mapping of allowances for an address mapping (address => mapping (address => uint)) allowances; /// @dev ERC20 total supply /// @return The current total supply of the resource function totalSupply() public constant returns(uint) { return resourceSupply; } /// @dev ERC20 balance of address /// @param _tokenOwner The address to look up /// @return The balance of the address function balanceOf(address _tokenOwner) public constant returns(uint balance) { return holdings[_tokenOwner]; } /// @dev Total resources frozen for an address /// @param _tokenOwner The address to look up /// @return The frozen balance of the address function frozenTokens(address _tokenOwner) public constant returns(uint balance) { return frozenHoldings[_tokenOwner]; } /// @dev The allowance for a spender on an account /// @param _tokenOwner The account that allows withdrawels /// @param _spender The account that is allowed to withdraw /// @return The amount remaining in the allowance function allowance(address _tokenOwner, address _spender) public constant returns(uint remaining) { return allowances[_tokenOwner][_spender]; } /// @dev Only run if player has at least some amount of tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens required modifier hasAvailableTokens(address _owner, uint _tokens) { require(holdings[_owner] - frozenHoldings[_owner] >= _tokens); _; } /// @dev Only run if player has at least some amount of tokens frozen /// @param _owner The owner of the tokens /// @param _tokens The amount of frozen tokens required modifier hasFrozenTokens(address _owner, uint _tokens) { require(frozenHoldings[_owner] >= _tokens); _; } /// @dev Set up the exact same state in each resource constructor() public { // God gets 200 to put on exchange holdings[msg.sender] = 200; resourceSupply = 200; } /// @dev The resources interface can burn tokens for building /// roads or houses /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to burn function interfaceBurnTokens(address _owner, uint _tokens) public onlyInterfaceContract hasAvailableTokens(_owner, _tokens) { holdings[_owner] -= _tokens; resourceSupply -= _tokens; // Pretend the tokens were sent to 0x0 emit Transfer(_owner, 0x0, _tokens); } /// @dev The resources interface contract can mint tokens for houses /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to burn function interfaceMintTokens(address _owner, uint _tokens) public onlyInterfaceContract { holdings[_owner] += _tokens; resourceSupply += _tokens; // Pretend the tokens were sent from the interface contract emit Transfer(interfaceContract, _owner, _tokens); } /// @dev The interface can freeze tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to freeze function interfaceFreezeTokens(address _owner, uint _tokens) public onlyInterfaceContract hasAvailableTokens(_owner, _tokens) { frozenHoldings[_owner] += _tokens; } /// @dev The interface can thaw tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to thaw function interfaceThawTokens(address _owner, uint _tokens) public onlyInterfaceContract hasFrozenTokens(_owner, _tokens) { frozenHoldings[_owner] -= _tokens; } /// @dev The interface can transfer tokens /// @param _from The owner of the tokens /// @param _to The new owner of the tokens /// @param _tokens The amount of tokens to transfer function interfaceTransfer(address _from, address _to, uint _tokens) public onlyInterfaceContract { assert(holdings[_from] >= _tokens); holdings[_from] -= _tokens; holdings[_to] += _tokens; emit Transfer(_from, _to, _tokens); } /// @dev The interface can transfer frozend tokens /// @param _from The owner of the tokens /// @param _to The new owner of the tokens /// @param _tokens The amount of frozen tokens to transfer function interfaceFrozenTransfer(address _from, address _to, uint _tokens) public onlyInterfaceContract hasFrozenTokens(_from, _tokens) { // Make sure to deduct the tokens from both the total and frozen amounts holdings[_from] -= _tokens; frozenHoldings[_from] -= _tokens; holdings[_to] += _tokens; emit Transfer(_from, _to, _tokens); } /// @dev ERC20 transfer /// @param _to The address to transfer to /// @param _tokens The amount of tokens to transfer function transfer(address _to, uint _tokens) public hasAvailableTokens(msg.sender, _tokens) returns(bool success) { holdings[_to] += _tokens; holdings[msg.sender] -= _tokens; emit Transfer(msg.sender, _to, _tokens); return true; } /// @dev ERC20 approve /// @param _spender The address to approve /// @param _tokens The amount of tokens to approve function approve(address _spender, uint _tokens) public returns(bool success) { allowances[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } /// @dev ERC20 transfer from /// @param _from The address providing the allowance /// @param _to The address using the allowance /// @param _tokens The amount of tokens to transfer function transferFrom(address _from, address _to, uint _tokens) public hasAvailableTokens(_from, _tokens) returns(bool success) { require(allowances[_from][_to] >= _tokens); holdings[_to] += _tokens; holdings[_from] -= _tokens; allowances[_from][_to] -= _tokens; emit Transfer(_from, _to, _tokens); return true; } } // File: contracts/resources/KingOfEthResourceWood.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth Resource: Wood /// @author Anthony Burzillo <[email protected]> /// @dev ERC20 contract for the wood resource contract KingOfEthResourceWood is KingOfEthResource { /// @dev The ERC20 token name string public constant name = "King of Eth Resource: Wood"; /// @dev The ERC20 token symbol string public constant symbol = "KEWO"; }
The allowance for a spender on an account _tokenOwner The account that allows withdrawels _spender The account that is allowed to withdraw return The amount remaining in the allowance
function allowance(address _tokenOwner, address _spender) public constant returns(uint remaining) { return allowances[_tokenOwner][_spender]; }
416,166
// 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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 pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwap(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtils.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ) .mul(v.feePerToken) .div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY(_getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(WITHDRAW_FEE_DECAY_TIME); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf(address(this)); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub(self.balances[i]); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; }
Calculate the amount of underlying token available to withdraw when withdrawing via only single token account the address that is withdrawing tokens tokenAmount the amount of LP token to burn tokenIndex index of which token will be withdrawn return availableTokenAmount calculated amount of underlying token available to withdraw/
function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); }
35,131
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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(to).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 "../../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 "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // 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 "../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 "../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); } 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 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol'; import './ERC721Ownable.sol'; import './ERC721WithRoyalties.sol'; /// @title ERC721Full /// @dev This contains all the different overrides needed on /// ERC721 / Enumerable / URIStorage / Royalties /// @author Simon Fremaux (@dievardump) abstract contract ERC721Full is ERC721Ownable, ERC721Burnable, ERC721WithRoyalties { /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC721, ERC721WithRoyalties) returns (bool) { return // either ERC721Enumerable ERC721Enumerable.supportsInterface(interfaceId) || // or Royalties ERC721WithRoyalties.supportsInterface(interfaceId); } /// @inheritdoc ERC721 function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /// @inheritdoc ERC721Ownable function isApprovedForAll(address owner_, address operator) public view override(ERC721, ERC721Ownable) returns (bool) { return ERC721Ownable.isApprovedForAll(owner_, operator); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '../OpenSea/BaseOpenSea.sol'; /// @title ERC721Ownable /// @author Simon Fremaux (@dievardump) contract ERC721Ownable is Ownable, ERC721Enumerable, BaseOpenSea { /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_ ) ERC721(name_, symbol_) { // set contract uri if present if (bytes(contractURI_).length > 0) { _setContractURI(contractURI_); } // set OpenSea proxyRegistry for gas-less trading if present if (address(0) != openseaProxyRegistry_) { _setOpenSeaRegistry(openseaProxyRegistry_); } } /// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user /// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy /// @inheritdoc ERC721 function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { // allows gas less trading on OpenSea if (isOwnersOpenSeaProxy(owner, operator)) { return true; } return super.isApprovedForAll(owner, operator); } /// @notice Helper for the owner of the contract to set the new contract URI /// @dev needs to be owner /// @param contractURI_ new contract URI function setContractURI(string memory contractURI_) external onlyOwner { _setContractURI(contractURI_); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../Royalties/ERC2981/IERC2981Royalties.sol'; import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol'; /// @dev This is a contract used for royalties on various platforms /// @author Simon Fremaux (@dievardump) contract ERC721WithRoyalties is IERC2981Royalties, IRaribleSecondarySales { function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || interfaceId == type(IRaribleSecondarySales).interfaceId; } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256, uint256) public view virtual override returns (address _receiver, uint256 _royaltyAmount) { _receiver = address(this); _royaltyAmount = 0; } /// @inheritdoc IRaribleSecondarySales function getFeeRecipients(uint256 tokenId) public view override returns (address payable[] memory recipients) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = royaltyInfo(tokenId, 10000); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); } } /// @inheritdoc IRaribleSecondarySales function getFeeBps(uint256 tokenId) public view override returns (uint256[] memory fees) { // using ERC2981 implementation to get the amount (, uint256 amount) = royaltyInfo(tokenId, 10000); if (amount != 0) { fees = new uint256[](1); fees[0] = amount; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's support contract BaseOpenSea { string private _contractURI; ProxyRegistry private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Helper for OpenSea gas-less trading /// @dev Allows to check if `operator` is owner's OpenSea proxy /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { ProxyRegistry proxyRegistry = _proxyRegistry; return // we have a proxy registry address address(proxyRegistry) != address(0) && // current operator is owner's proxy address address(proxyRegistry.proxies(owner)) == operator; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = ProxyRegistry(proxyRegistryAddress); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IRaribleSecondarySales { /// @notice returns a list of royalties recipients /// @param tokenId the token Id to check for /// @return all the recipients for tokenId function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); /// @notice returns a list of royalties amounts /// @param tokenId the token Id to check for /// @return all the amounts for tokenId function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IRenderer /// @author Simon Fremaux (@dievardump) interface IRenderer { /// @dev Rendering function; /// @param name the seedling name /// @param tokenId the tokenId /// @param seed the seed /// @return the json function render( string memory name, uint256 tokenId, bytes32 seed ) external pure returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title IVariety interface /// @author Simon Fremaux (@dievardump) interface IVariety is IERC721 { /// @notice mint `seeds.length` token(s) to `to` using `seeds` /// @param to token recipient /// @param seeds each token seed function plant(address to, bytes32[] memory seeds) external returns (uint256); /// @notice this function returns the seed associated to a tokenId /// @param tokenId to get the seed of function getTokenSeed(uint256 tokenId) external view returns (bytes32); /// @notice This function allows an owner to ask for a seed update /// this can be needed because although I test the contract as much as possible, /// it might be possible that one token does not render because the seed creates /// error or even "out of gas" computation. That's why this would allow an owner /// in such case, to request for a seed change that will then be triggered by Sower /// @param tokenId id to regenerate seed for function requestSeedChange(uint256 tokenId) external; /// @notice This function allows Sower to answer to a seed change request /// in the event where a seed would produce errors of rendering /// 1) this function can only be called by Sower if the token owner /// asked for a new seed /// 2) this function will only be called if there is a rendering error /// or, Vitalik Buterin forbid, a duplicate /// @param tokenId id to regenerate seed for function changeSeedAfterRequest(uint256 tokenId) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//////************@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@/////*******************@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///***********************@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///**************************@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///**********/**************/*@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///////****/****************//@@@@@ // @@@*********@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(///////////*****************//@@@@@@ // @@@**************//////@@@@@@@@@@@@@@@@@@@((////////////***************//@@@@@@@ // @@@*********************////@@@@@@@@@@@@@((///////////////************//@@@@@@@@ // @@@@//**************//***//////@@@@@@@@@@(///////////////////*******//@@@@@@@@@@ // @@@@@/*****************////////((@@@@@@@((///((////////////////***//@@@@@@@@@@@@ // @@@@@@//*************////////////((@@@@@((//((////////////////////@@@@@@@@@@@@@@ // @@@@@@@//**********///////////////((@@@@((((//////////////////@@@@@@@@@@@@@@@@@@ // @@@@@@@@///******//////////////((//((@@@(((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@//*///////////////////(//((@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@////////////////////(((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@/((((/////////////((((/@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@((((((((@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@###(((((((((((((((((((((((((###@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@####################################@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@#############################################@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import './IVariety.sol'; import '../NFT/ERC721Helpers/ERC721Full.sol'; /// @title Variety Contract /// @author Simon Fremaux (@dievardump) contract Variety is IVariety, ERC721Full { event SeedChangeRequest(uint256 indexed tokenId, address indexed operator); // seedlings Sower address public sower; // last tokenId uint256 public lastTokenId; // each token seed mapping(uint256 => bytes32) internal tokenSeed; // names mapping(uint256 => string) public names; // useNames mapping(bytes32 => bool) public usedNames; // tokenIds with a request for seeds change mapping(uint256 => bool) internal seedChangeRequests; modifier onlySower() { require(msg.sender == sower, 'Not Sower.'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_ ) ERC721Ownable(name_, symbol_, contractURI_, openseaProxyRegistry_) { sower = sower_; } /// @notice mint `seeds.length` token(s) to `to` using `seeds` /// @param to token recipient /// @param seeds each token seed function plant(address to, bytes32[] memory seeds) external virtual override onlySower returns (uint256) { uint256 tokenId = lastTokenId; for (uint256 i; i < seeds.length; i++) { tokenId++; _safeMint(to, tokenId); tokenSeed[tokenId] = seeds[i]; } lastTokenId = tokenId; return tokenId; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Full, IERC165) returns (bool) { return super.supportsInterface(interfaceId); } /// @notice tokenURI override that returns a data:json application /// @inheritdoc ERC721 function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); return _render(tokenId, tokenSeed[tokenId]); } /// @notice ERC2981 support - 4% royalties sent to Sower /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256, uint256 value) public view override returns (address receiver, uint256 royaltyAmount) { receiver = sower; royaltyAmount = (value * 400) / 10000; } /// @inheritdoc IVariety function getTokenSeed(uint256 tokenId) external view override returns (bytes32) { require(_exists(tokenId), 'TokenSeed query for nonexistent token'); return tokenSeed[tokenId]; } /// @inheritdoc IVariety function requestSeedChange(uint256 tokenId) external override { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); seedChangeRequests[tokenId] = true; emit SeedChangeRequest(tokenId, msg.sender); } /// @inheritdoc IVariety function changeSeedAfterRequest(uint256 tokenId) external override onlySower { require(seedChangeRequests[tokenId] == true, 'No request for token.'); seedChangeRequests[tokenId] = false; tokenSeed[tokenId] = keccak256( abi.encode( tokenSeed[tokenId], block.timestamp, block.difficulty, blockhash(block.number - 1) ) ); } /// @notice Function allowing an owner to set the seedling name /// User needs to be extra careful. Some characters might completly break the token. /// Since the metadata are generated in the contract. /// if this ever happens, you can simply reset the name to nothing or for something else /// @dev sender must be tokenId owner /// @param tokenId the token to name /// @param seedlingName the name function setName(uint256 tokenId, string memory seedlingName) external virtual { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); bytes32 byteName = keccak256(abi.encodePacked(seedlingName)); // if the name is not empty, verify it is not used if (bytes(seedlingName).length > 0) { require(usedNames[byteName] == false, 'Name already used'); usedNames[byteName] = true; } // if it already has a name, mark all name as unused string memory oldName = names[tokenId]; if (bytes(oldName).length > 0) { byteName = keccak256(abi.encodePacked(oldName)); usedNames[byteName] = false; } names[tokenId] = seedlingName; } /// @notice function to get a token name /// @dev token must exist /// @param tokenId the token to get the name of /// @return the token name function getName(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), 'Unknown token'); return _getName(tokenId); } /// @dev internal function to get the name. Should be overrode by actual Variety contract /// @param tokenId the token to get the name of /// @return the token name function _getName(uint256 tokenId) internal view virtual returns (string memory) { return bytes(names[tokenId]).length > 0 ? names[tokenId] : 'Variety'; } /// @notice Function allowing to check the rendering for a given seed /// This allows to know what a seed would render without minting /// @param seed the seed to render /// @return the json function renderSeed(bytes32 seed) public view returns (string memory) { return _render(0, seed); } /// @dev Rendering function; should be overrode by the actual seedling contract /// @param tokenId the tokenId /// @param seed the seed /// @return the json function _render(uint256 tokenId, bytes32 seed) internal view virtual returns (string memory) { seed; return string( abi.encodePacked( 'data:application/json;utf8,{"name":"', _getName(tokenId), '"}' ) ); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Variety.sol'; /// @title VarietyRepot Contract /// @author Simon Fremaux (@dievardump) contract VarietyRepot is Variety { event SeedlingsRepoted(address user, uint256[] ids); // this is the address we will repot tokens from address public oldVariety; // during the first 3 days after the start of migration // we do not allow people to name, so people with names // in the old contract have time to migrate with theirs uint256 public disabledNamingUntil; /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_, address oldVariety_ ) Variety(name_, symbol_, contractURI_, openseaProxyRegistry_, sower_) { sower = sower_; if (address(0) != oldVariety_) { oldVariety = oldVariety_; } // during 3 days, naming will be disabled as to give time to people to migrate from the old contract // to the new and keep their name disabledNamingUntil = block.timestamp + 3 days; } /// @inheritdoc Variety function plant(address, bytes32[] memory) external view override onlySower returns (uint256) { // this ensure that noone, even Sower, can directly mint tokens on this contract // they can only be created through the repoting method revert('No direct planting, only repot.'); } /// @notice Function allowing an owner to set the seedling name /// User needs to be extra careful. Some characters might completly break the token. /// Since the metadata are generated in the contract. /// if this ever happens, you can simply reset the name to nothing or for something else /// @dev sender must be tokenId owner /// @param tokenId the token to name /// @param seedlingName the name function setName(uint256 tokenId, string memory seedlingName) external override { require( block.timestamp > disabledNamingUntil, 'Naming feature disabled.' ); require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); _setName(tokenId, seedlingName); } /// @notice Checks if the string is valid (0-9a-zA-Z,- ) with no leading, trailing or consecutives spaces /// This function is a modified version of the one in the Hashmasks contract /// @dev Explain to a developer any extra details /// @param str the name to validate /// @return if the name is valid function isNameValid(string memory str) public pure returns (bool) { bytes memory strBytes = bytes(str); if (strBytes.length < 1) return false; if (strBytes.length > 32) return false; // Cannot be longer than 32 characters if (strBytes[0] == 0x20) return false; // Leading space if (strBytes[strBytes.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar; bytes1 char; uint8 charCode; for (uint256 i; i < strBytes.length; i++) { char = strBytes[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces charCode = uint8(char); if ( !(charCode >= 97 && charCode <= 122) && // a - z !(charCode >= 65 && charCode <= 90) && // A - Z !(charCode >= 48 && charCode <= 57) && // 0 - 9 !(charCode == 32) && // space !(charCode == 44) && // , !(charCode == 45) // - ) { return false; } lastChar = char; } return true; } /// @notice Slugify a name (tolower and replace all non 0-9az by -) /// @param str the string to keyIfy /// @return the key function slugify(string memory str) public pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory lowerCase = new bytes(strBytes.length); uint8 charCode; bytes1 char; for (uint256 i; i < strBytes.length; i++) { char = strBytes[i]; charCode = uint8(char); // if 0-9, a-z use the character if ( (charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 122) ) { lowerCase[i] = char; } else if (charCode >= 65 && charCode <= 90) { // if A-Z, use lowercase lowerCase[i] = bytes1(charCode + 32); } else { // for all others, return a - lowerCase[i] = 0x2D; } } return string(lowerCase); } /// @notice repot (migrate and burn) the seedlings of `users` from the old variety contract to the new one /// to give them the exact same token id, seed and custom name if valid, on this contract /// The old token is burned (deleted) forever from the old contract /// @dev we do not need to check that `user` we transferFrom is not the current contract, because _safeMint /// would fail if we tried to mint the same tokenId twice /// @param users an array of users /// @param maxTokensAtOnce a limit of token to migrate at once, since a few users have strong hands function repotUsersSeedlings( address[] memory users, uint256 maxTokensAtOnce ) external { require( // only the contract owner msg.sender == owner() || // or someone trying to migrate their own tokens can call this function (users.length == 1 && users[0] == msg.sender), 'Not allowed to migrate.' ); Variety oldVariety_ = Variety(oldVariety); address me = address(this); address user; uint256 migrated; for (uint256 j; j < users.length && (migrated < maxTokensAtOnce); j++) { user = users[j]; uint256 userBalance = oldVariety_.balanceOf(user); if (userBalance == 0) continue; uint256 end = userBalance; // some users might have too many tokens to do that in one transaction if (userBalance > (maxTokensAtOnce - migrated)) { end = (maxTokensAtOnce - migrated); } uint256[] memory ids = new uint256[](end); uint256 tokenId; bytes32 seed; bytes32 slugBytes; string memory seedlingName; for (uint256 i; i < end; i++) { // get the last token id owned by the user // this is a bit cheaper than always getting index 0 // because when removing last there is no "reorg" in the EnumerableSet tokenId = oldVariety_.tokenOfOwnerByIndex( user, userBalance - (i + 1) // this takes the last id in the user list ); // get the token seed seed = oldVariety_.getTokenSeed(tokenId); // get the token name seedlingName = oldVariety_.getName(tokenId); // burn the old token first oldVariety_.burn(tokenId); // create the same token id in this contract for this user _safeMint(user, tokenId, ''); // set exact same seed tokenSeed[tokenId] = seed; // if the seedling had a name and the name is valid if ( bytes(seedlingName).length > 0 && isNameValid(seedlingName) ) { slugBytes = keccak256(bytes(slugify(seedlingName))); // and is not already used if (!usedNames[slugBytes]) { // then use it usedNames[slugBytes] = true; names[tokenId] = seedlingName; } } ids[i] = tokenId; } migrated += end; emit SeedlingsRepoted(user, ids); } } /// @dev allows to set a name internally. /// checks that the name is valid and not used, else throws /// @param tokenId the token to name /// @param seedlingName the name function _setName(uint256 tokenId, string memory seedlingName) internal { bytes32 slugBytes; // if the name is not empty, require that it's valid and not used if (bytes(seedlingName).length > 0) { require(isNameValid(seedlingName) == true, 'Invalid name.'); // also requires the name is not already used slugBytes = keccak256(bytes(slugify(seedlingName))); require(usedNames[slugBytes] == false, 'Name already used.'); // set as used usedNames[slugBytes] = true; } // if it already has a name, mark the old name as unused string memory oldName = names[tokenId]; if (bytes(oldName).length > 0) { slugBytes = keccak256(bytes(slugify(oldName))); usedNames[slugBytes] = false; } names[tokenId] = seedlingName; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../VarietyRepot.sol'; import '../IRenderer.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; /// @title _512PrintRepot /// @author Simon Fremaux (@dievardump) contract _512PrintRepot is VarietyRepot { using Strings for uint256; IRenderer public renderer; /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract /// @param renderer_ the renderer contract /// @param oldContract_ the oldContract for migration constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_, address renderer_, address oldContract_ ) VarietyRepot( name_, symbol_, contractURI_, openseaProxyRegistry_, sower_, oldContract_ ) { renderer = IRenderer(renderer_); } /// @notice This function is a function that allows to update the current renderer /// to a version where "rounded-stroke-gradient" misprints are fixed /// this function will only be called in the case of a positive vote from 512Print holders function updateRenderer(address newRenderer) external onlyOwner { renderer = IRenderer(newRenderer); } /// @dev internal function to get the name. Should be overrode by actual Variety contract /// @param tokenId the token to get the name of /// @return seedlingName the token name function _getName(uint256 tokenId) internal view override returns (string memory seedlingName) { seedlingName = names[tokenId]; if (bytes(seedlingName).length == 0) { seedlingName = string( abi.encodePacked('512Print.sol #', tokenId.toString()) ); } } /// @dev Rendering function; should be overrode by the actual seedling contract /// @param tokenId the tokenId /// @param seed the seed /// @return the json function _render(uint256 tokenId, bytes32 seed) internal view virtual override returns (string memory) { return IRenderer(renderer).render(_getName(tokenId), tokenId, seed); } }
This function is a function that allows to update the current renderer to a version where "rounded-stroke-gradient" misprints are fixed this function will only be called in the case of a positive vote from 512Print holders
function updateRenderer(address newRenderer) external onlyOwner { renderer = IRenderer(newRenderer); }
10,311,310
pragma solidity 0.5.10; import "./interfaces/ICertifier.sol"; import "./interfaces/IRandomAuRa.sol"; import "./interfaces/IStakingAuRa.sol"; import "./interfaces/ITxPermission.sol"; import "./interfaces/IValidatorSetAuRa.sol"; import "./upgradeability/UpgradeableOwned.sol"; /// @dev Controls the use of zero gas price by validators in service transactions, /// protecting the network against "transaction spamming" by malicious validators. /// The protection logic is declared in the `allowedTxTypes` function. contract TxPermission is UpgradeableOwned, ITxPermission { // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables, do not change their order, // and do not change their types! address[] internal _allowedSenders; /// @dev The address of the `Certifier` contract. ICertifier public certifierContract; /// @dev A boolean flag indicating whether the specified address is allowed /// to initiate transactions of any type. Used by the `allowedTxTypes` getter. /// See also the `addAllowedSender` and `removeAllowedSender` functions. mapping(address => bool) public isSenderAllowed; /// @dev The address of the `ValidatorSetAuRa` contract. IValidatorSetAuRa public validatorSetContract; mapping(address => uint256) internal _deployerInputLengthLimit; /// @dev The min gas price allowed for a specified sender, in Wei. /// Zero means default min gas price. mapping(address => uint256) public senderMinGasPrice; // ============================================== Constants ======================================================= /// @dev A constant that defines a regular block gas limit. /// Used by the `blockGasLimit` public getter. uint256 public constant BLOCK_GAS_LIMIT = 12500000; /// @dev A constant that defines a reduced block gas limit. /// Used by the `blockGasLimit` public getter. uint256 public constant BLOCK_GAS_LIMIT_REDUCED = 4000000; // ================================================ Events ======================================================== /// @dev Emitted by the `setDeployerInputLengthLimit` function. /// @param deployer The address of a contract deployer. /// @param limit The maximum number of bytes in `input` field of deployment transaction. event DeployerInputLengthLimitSet(address indexed deployer, uint256 limit); /// @dev Emitted by the `setSenderMinGasPrice` function. /// @param sender The address of transaction sender. /// @param minGasPrice The min gas price in Wei. Zero to reset to default min gas price. event SenderMinGasPriceSet(address indexed sender, uint256 minGasPrice); // ============================================== Modifiers ======================================================= /// @dev Ensures the `initialize` function was called before. modifier onlyInitialized { require(isInitialized()); _; } // =============================================== Setters ======================================================== /// @dev Initializes the contract at network startup. /// Can only be called by the constructor of the `InitializerAuRa` contract or owner. /// @param _allowed The addresses for which transactions of any type must be allowed. /// See the `allowedTxTypes` getter. /// @param _certifier The address of the `Certifier` contract. It is used by `allowedTxTypes` function to know /// whether some address is explicitly allowed to use zero gas price. /// @param _validatorSet The address of the `ValidatorSetAuRa` contract. function initialize( address[] calldata _allowed, address _certifier, address _validatorSet ) external { require(block.number == 0 || msg.sender == _admin()); require(!isInitialized()); require(_certifier != address(0)); require(_validatorSet != address(0)); for (uint256 i = 0; i < _allowed.length; i++) { _addAllowedSender(_allowed[i]); } certifierContract = ICertifier(_certifier); validatorSetContract = IValidatorSetAuRa(_validatorSet); } /// @dev Adds the address for which transactions of any type must be allowed. /// Can only be called by the `owner`. See also the `allowedTxTypes` getter. /// @param _sender The address for which transactions of any type must be allowed. function addAllowedSender(address _sender) public onlyOwner onlyInitialized { _addAllowedSender(_sender); } /// @dev Removes the specified address from the array of addresses allowed /// to initiate transactions of any type. Can only be called by the `owner`. /// See also the `addAllowedSender` function and `allowedSenders` getter. /// @param _sender The removed address. function removeAllowedSender(address _sender) public onlyOwner onlyInitialized { require(isSenderAllowed[_sender]); uint256 allowedSendersLength = _allowedSenders.length; for (uint256 i = 0; i < allowedSendersLength; i++) { if (_sender == _allowedSenders[i]) { _allowedSenders[i] = _allowedSenders[allowedSendersLength - 1]; _allowedSenders.length--; break; } } isSenderAllowed[_sender] = false; } /// @dev Sets the limit of `input` transaction field length in bytes /// for contract deployment transaction made by the specified deployer. /// @param _deployer The address of a contract deployer. /// @param _limit The maximum number of bytes in `input` field of deployment transaction. /// Set it to zero to reset to default 24Kb limit defined by EIP 170. function setDeployerInputLengthLimit(address _deployer, uint256 _limit) public onlyOwner onlyInitialized { _deployerInputLengthLimit[_deployer] = _limit; emit DeployerInputLengthLimitSet(_deployer, _limit); } /// @dev Sets the min gas price allowed for a specified sender. /// @param _sender The address of transaction sender. /// @param _minGasPrice The min gas price in Wei. Zero to reset to default min gas price. function setSenderMinGasPrice(address _sender, uint256 _minGasPrice) public onlyOwner onlyInitialized { senderMinGasPrice[_sender] = _minGasPrice; emit SenderMinGasPriceSet(_sender, _minGasPrice); } // =============================================== Getters ======================================================== /// @dev Returns the contract's name recognizable by node's engine. function contractName() public pure returns(string memory) { return "TX_PERMISSION_CONTRACT"; } /// @dev Returns the contract name hash needed for node's engine. function contractNameHash() public pure returns(bytes32) { return keccak256(abi.encodePacked(contractName())); } /// @dev Returns the contract's version number needed for node's engine. function contractVersion() public pure returns(uint256) { return 3; } /// @dev Returns the list of addresses allowed to initiate transactions of any type. /// For these addresses the `allowedTxTypes` getter always returns the `ALL` bit mask /// (see https://openethereum.github.io/Permissioning.html#how-it-works-1). function allowedSenders() public view returns(address[] memory) { return _allowedSenders; } /// @dev Defines the allowed transaction types which may be initiated by the specified sender with /// the specified gas price and data. Used by node's engine each time a transaction is about to be /// included into a block. See https://openethereum.github.io/Permissioning.html#how-it-works-1 /// @param _sender Transaction sender address. /// @param _to Transaction recipient address. If creating a contract, the `_to` address is zero. /// @param _value Transaction amount in wei. /// @param _gasPrice Gas price in wei for the transaction. /// @param _data Transaction data. /// @return `uint32 typesMask` - Set of allowed transactions for `_sender` depending on tx `_to` address, /// `_gasPrice`, and `_data`. The result is represented as a set of flags: /// 0x01 - basic transaction (e.g. ether transferring to user wallet); /// 0x02 - contract call; /// 0x04 - contract creation; /// 0x08 - private transaction. /// `bool cache` - If `true` is returned, the same permissions will be applied from the same /// `_sender` without calling this contract again. function allowedTxTypes( address _sender, address _to, uint256 _value, uint256 _gasPrice, bytes memory _data ) public view returns(uint32 typesMask, bool cache) { if (isSenderAllowed[_sender]) { // Let the `_sender` initiate any transaction if the `_sender` is in the `allowedSenders` list return (ALL, false); } if (_to == address(0) && _data.length > deployerInputLengthLimit(_sender)) { // Don't let to deploy too big contracts return (NONE, false); } // Get the called function's signature bytes4 signature = bytes4(0); assembly { signature := shl(224, mload(add(_data, 4))) } if (_to == validatorSetContract.randomContract()) { if (signature == COMMIT_HASH_SIGNATURE && _data.length > 4+32) { bytes32 numberHash; assembly { numberHash := mload(add(_data, 36)) } return (IRandomAuRa(_to).commitHashCallable(_sender, numberHash) ? CALL : NONE, false); } else if ( (signature == REVEAL_NUMBER_SIGNATURE || signature == REVEAL_SECRET_SIGNATURE) && _data.length == 4+32 ) { uint256 num; assembly { num := mload(add(_data, 36)) } return (IRandomAuRa(_to).revealNumberCallable(_sender, num) ? CALL : NONE, false); } else { return (NONE, false); } } if (_to == address(validatorSetContract)) { // The rules for the ValidatorSetAuRa contract if (signature == EMIT_INITIATE_CHANGE_SIGNATURE) { // The `emitInitiateChange()` can be called by anyone // if `emitInitiateChangeCallable()` returns `true` return (validatorSetContract.emitInitiateChangeCallable() ? CALL : NONE, false); } else if (signature == REPORT_MALICIOUS_SIGNATURE && _data.length >= 4+64) { address maliciousMiningAddress; uint256 blockNumber; assembly { maliciousMiningAddress := mload(add(_data, 36)) blockNumber := mload(add(_data, 68)) } // The `reportMalicious()` can only be called by the validator's mining address // when the calling is allowed (bool callable,) = validatorSetContract.reportMaliciousCallable( _sender, maliciousMiningAddress, blockNumber ); return (callable ? CALL : NONE, false); } else if (_gasPrice > 0) { // The other functions of ValidatorSetAuRa contract can be called // by anyone except validators' mining addresses if gasPrice is not zero return (validatorSetContract.isValidator(_sender) ? NONE : CALL, false); } } if (validatorSetContract.isValidator(_sender) && _gasPrice > 0) { // Let the validator's mining address send their accumulated tx fees to some wallet return (_sender.balance > 0 ? BASIC : NONE, false); } if (validatorSetContract.isValidator(_to)) { // Validator's mining address can't receive any coins return (NONE, false); } // Don't let the `_sender` use a zero gas price, if it is not explicitly allowed by the `Certifier` contract if (_gasPrice == 0) { return (certifierContract.certifiedExplicitly(_sender) ? ALL : NONE, false); } // Disallow invalid gas price for the specified sender if (_gasPrice < senderMinGasPrice[_sender]) { return (NONE, false); } // In other cases let the `_sender` create any transaction with non-zero gas price return (ALL, false); } /// @dev Returns the current block gas limit which depends on the stage of the current /// staking epoch: the block gas limit is temporarily reduced for the latest block of the epoch. function blockGasLimit() public view returns(uint256) { address stakingContract = validatorSetContract.stakingContract(); uint256 stakingEpochEndBlock = IStakingAuRa(stakingContract).stakingEpochEndBlock(); if (block.number == stakingEpochEndBlock - 1 || block.number == stakingEpochEndBlock) { return BLOCK_GAS_LIMIT_REDUCED; } return BLOCK_GAS_LIMIT; } /// @dev Returns the limit of `input` transaction field length in bytes /// for contract deployment transaction made by the specified deployer. /// @param _deployer The address of a contract deployer. function deployerInputLengthLimit(address _deployer) public view returns(uint256) { uint256 limit = _deployerInputLengthLimit[_deployer]; if (limit != 0) { return limit; } else { return 30720; // default EIP 170 limit (24 Kb + overhead) } } /// @dev Returns a boolean flag indicating if the `initialize` function has been called. function isInitialized() public view returns(bool) { return validatorSetContract != IValidatorSetAuRa(0); } // ============================================== Internal ======================================================== // Allowed transaction types mask uint32 internal constant NONE = 0; uint32 internal constant ALL = 0xffffffff; uint32 internal constant BASIC = 0x01; uint32 internal constant CALL = 0x02; uint32 internal constant CREATE = 0x04; uint32 internal constant PRIVATE = 0x08; // Function signatures // bytes4(keccak256("commitHash(bytes32,bytes)")) bytes4 internal constant COMMIT_HASH_SIGNATURE = 0x0b61ba85; // bytes4(keccak256("emitInitiateChange()")) bytes4 internal constant EMIT_INITIATE_CHANGE_SIGNATURE = 0x93b4e25e; // bytes4(keccak256("reportMalicious(address,uint256,bytes)")) bytes4 internal constant REPORT_MALICIOUS_SIGNATURE = 0xc476dd40; // bytes4(keccak256("revealSecret(uint256)")) bytes4 internal constant REVEAL_SECRET_SIGNATURE = 0x98df67c6; // bytes4(keccak256("revealNumber(uint256)")) bytes4 internal constant REVEAL_NUMBER_SIGNATURE = 0xfe7d567d; /// @dev An internal function used by the `addAllowedSender` and `initialize` functions. /// @param _sender The address for which transactions of any type must be allowed. function _addAllowedSender(address _sender) internal { require(!isSenderAllowed[_sender]); require(_sender != address(0)); _allowedSenders.push(_sender); isSenderAllowed[_sender] = true; } }
Adds the address for which transactions of any type must be allowed. Can only be called by the `owner`. See also the `allowedTxTypes` getter. _sender The address for which transactions of any type must be allowed.
function addAllowedSender(address _sender) public onlyOwner onlyInitialized { _addAllowedSender(_sender); }
14,075,173
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../openzeppelin-solidity/contracts/token/ERC1155/ERC1155.sol"; import "../openzeppelin-solidity/contracts/token/ERC1155/utils/ERC1155Holder.sol"; contract OnOrder is ERC1155Holder { DigitalItems private s_digitalItems; constructor() { } function Init(DigitalItems digitalItems) public { s_digitalItems = digitalItems; } function Item_SendTo(address xPeer, uint256 idItem, uint32 amountItem) public { s_digitalItems.setApprovalForAll(xPeer,true); s_digitalItems.safeTransferFrom(address(this), xPeer, idItem, amountItem, "0x0"); } function Item_RecvFrom(address xOwner, uint256 idItem, uint32 amountItem) public { s_digitalItems.safeTransferFrom(xOwner, address(this), idItem, amountItem, "0x0"); } } contract DigitalItems is ERC1155 { address private s_xDeployer; OnOrder private s_onOrder; constructor() ERC1155("https://github.com/zombietimes") { require(msg.sender != address(0)); s_xDeployer = msg.sender; s_onOrder = new OnOrder(); s_onOrder.Init(this); } mapping(uint256 => ItemInfo) public s_items; function Item_Create(uint32 amountItem, string memory name) public { uint256 idItem = Item_GetIdItem(msg.sender, name); require(s_items[idItem].creater == address(0x0), "[ERR]Already exist."); s_items[idItem].creater = msg.sender; s_items[idItem].name = name; _mint(msg.sender, idItem, amountItem, ""); } function Item_GetIdItem(address xCreater, string memory name) public pure returns(uint256 idItem) { idItem = uint256(keccak256(abi.encodePacked(xCreater, name))); } function Item_Add(uint256 idItem, uint32 amountItem) public { require(s_items[idItem].creater == msg.sender, "[ERR]Not creater."); _mint(msg.sender, idItem, amountItem, ""); } function Item_Remove(uint256 idItem, uint32 amountItem) public { require(s_items[idItem].creater == msg.sender, "[ERR]Not creater."); _burn(msg.sender, idItem, amountItem); } function Item_GetBalance(address xOwner, uint256 idItem) public view returns(uint256 balance) { balance = balanceOf(xOwner, idItem); } mapping(address => uint256) public s_balances; function Wei_Deposit() public payable { require(msg.sender != address(0)); s_balances[msg.sender] += msg.value; } function Wei_Withdraw() public payable { require(msg.sender != address(0)); uint256 balance = s_balances[msg.sender]; if(balance > 0){ s_balances[msg.sender] = 0; payable(msg.sender).transfer(balance); } } function Wei_GetBalance(address xOwner) public view returns(uint256 balance) { balance = s_balances[xOwner]; } uint8 constant ORDER_KIND_SELL = 0; uint8 constant ORDER_KIND_BUY = 1; uint8 constant ORDER_KIND_NUM = 2; struct Order { address xOwner; uint32 amountItem; } struct OrderInfo { uint32 indexStart; Order[] orderList; } struct PriceInfo { OrderInfo[ORDER_KIND_NUM] orderInfo; } struct ItemInfo { address creater; string name; mapping(uint256 => PriceInfo) prices; } modifier fromSender(uint256 idItem, uint32 amountItem) { uint256 amountItemBefore = balanceOf(msg.sender, idItem); require(amountItemBefore >= amountItem, "[ERR]Not enough Item."); _; } function AddOrderSell(uint256 idItem, uint32 price, uint32 amountItem) public fromSender(idItem, amountItem) { item_fromSenderToOnOrder(idItem, amountItem); s_items[idItem].prices[price].orderInfo[ORDER_KIND_SELL].orderList.push(Order(msg.sender, amountItem)); } function AddOrderBuy(uint256 idItem, uint32 price, uint32 amountItem) public { uint256 amountWei = amountItem * price; amountWei += getFeeBase(amountWei); // Fee payment by Buyer require(s_balances[msg.sender] >= amountWei, "[ERR]Not enough wei."); wei_fromSenderToOnOrder(amountWei); s_items[idItem].prices[price].orderInfo[ORDER_KIND_BUY].orderList.push(Order(msg.sender, amountItem)); setApprovalForAll(address(s_onOrder),true); } function GetOrderInfo(uint256 idItem, uint32 price, uint8 orderKind) public view returns(uint32 indexStart, uint32 listLen) { OrderInfo memory orderInfo = s_items[idItem].prices[price].orderInfo[orderKind]; indexStart = orderInfo.indexStart; listLen = uint32(orderInfo.orderList.length); } function GetOrder(uint256 idItem, uint32 price, uint8 orderKind, uint32 indexOrder) public view returns(address xOwner, uint32 amountItem){ OrderInfo memory orderInfo = s_items[idItem].prices[price].orderInfo[orderKind]; xOwner = orderInfo.orderList[indexOrder].xOwner; amountItem = orderInfo.orderList[indexOrder].amountItem; } uint8 constant SELF_KIND_SELLER = 0; uint8 constant SELF_KIND_BUYER = 1; function TryMatchingOrders(uint256 idItem, uint32 price, uint8 orderKindSelf, uint32 indexOrderSelf, uint32 amountItemReqSelf) public { OrderInfo storage s_orderInfoSelf = s_items[idItem].prices[price].orderInfo[orderKindSelf]; require(amountItemReqSelf <= s_orderInfoSelf.orderList[indexOrderSelf].amountItem, "[ERR]Not enough item amount."); (uint8 selfKind, uint8 orderKindPeer) = analyzeOrderKindInfo(orderKindSelf); OrderInfo storage s_orderInfoPeer = s_items[idItem].prices[price].orderInfo[orderKindPeer]; uint32 listLenPeer = uint32(s_orderInfoPeer.orderList.length); uint32 amountItemRemain = amountItemReqSelf; require(s_orderInfoPeer.indexStart < listLenPeer, "[ERR]No order."); for(uint32 indexOrderPeer = s_orderInfoPeer.indexStart; indexOrderPeer < listLenPeer; indexOrderPeer += 1){ uint32 amountItemPeer = s_orderInfoPeer.orderList[indexOrderPeer].amountItem; if(amountItemPeer != 0){ amountItemRemain = matching(idItem, price, selfKind, s_orderInfoSelf, s_orderInfoPeer, indexOrderSelf, indexOrderPeer, amountItemPeer, amountItemRemain); if(amountItemRemain <= 0){ break; } } } updateIndexStart(idItem, price, orderKindSelf); updateIndexStart(idItem, price, orderKindPeer); } function matching(uint256 idItem, uint32 price, uint8 selfKind, OrderInfo storage s_orderInfoSelf, OrderInfo storage s_orderInfoPeer, uint32 indexOrderSelf, uint32 indexOrderPeer, uint32 amountItemPeer, uint32 amountItemRemain) private returns(uint32 amountItemRemainNew) { uint32 amountItemDone = 0; if(s_orderInfoSelf.orderList[indexOrderSelf].xOwner != s_orderInfoPeer.orderList[indexOrderPeer].xOwner){ if(amountItemRemain <= amountItemPeer){ amountItemDone = amountItemRemain; amountItemRemainNew = 0; }else{ amountItemDone = amountItemPeer; amountItemRemainNew = amountItemRemain - amountItemDone; } s_orderInfoSelf.orderList[indexOrderSelf].amountItem -= amountItemDone; s_orderInfoPeer.orderList[indexOrderPeer].amountItem -= amountItemDone; if(amountItemDone > 0){ trade(idItem, price, selfKind, amountItemDone, s_orderInfoSelf.orderList[indexOrderSelf].xOwner, s_orderInfoPeer.orderList[indexOrderPeer].xOwner); } } } function CancelOrder(uint256 idItem, uint32 price, uint8 orderKindSelf, uint32 indexOrderSelf) public { OrderInfo storage s_orderInfoSelf = s_items[idItem].prices[price].orderInfo[orderKindSelf]; require(s_orderInfoSelf.orderList[indexOrderSelf].xOwner == msg.sender, "[ERR]Not owner."); uint32 amountItem = s_orderInfoSelf.orderList[indexOrderSelf].amountItem; s_orderInfoSelf.orderList[indexOrderSelf].amountItem = 0; updateIndexStart(idItem, price, orderKindSelf); (uint8 selfKind,) = analyzeOrderKindInfo(orderKindSelf); if(selfKind == SELF_KIND_SELLER){ // Item : xOnOrder > msg.sender item_fromOnOrderToSender(idItem, amountItem); }else{ // Wei : xOnOrder > msg.sender uint256 amountWei = amountItem * price; amountWei += getFeeBase(amountWei); wei_fromOnOrderToSender(amountWei); } emit infoCancel(idItem, price, orderKindSelf, indexOrderSelf, amountItem); } event infoCancel(uint256 idItem, uint32 price, uint8 orderKindSelf, uint32 indexOrderSelf, uint32 amountItem); function analyzeOrderKindInfo(uint8 orderKindSelf) private pure returns(uint8 selfKind, uint8 orderKindPeer) { if(orderKindSelf == ORDER_KIND_SELL){ selfKind = SELF_KIND_SELLER; orderKindPeer = ORDER_KIND_BUY; }else if(orderKindSelf == ORDER_KIND_BUY){ selfKind = SELF_KIND_BUYER; orderKindPeer = ORDER_KIND_SELL; }else { require((orderKindSelf == ORDER_KIND_SELL)||(orderKindSelf == ORDER_KIND_BUY), "[ERR]Invalid order kind."); } } function updateIndexStart(uint256 idItem, uint32 price, uint8 orderKind) private { OrderInfo storage s_orderInfo = s_items[idItem].prices[price].orderInfo[orderKind]; uint32 listLen = uint32(s_orderInfo.orderList.length); uint32 indexOrder; for(indexOrder = s_orderInfo.indexStart; indexOrder < listLen; indexOrder += 1){ if(s_orderInfo.orderList[indexOrder].amountItem != 0){ break; } } if(indexOrder > s_orderInfo.indexStart){ s_orderInfo.indexStart = indexOrder; } } function trade(uint256 idItem, uint32 price, uint8 selfKind, uint32 amountItemDone, address xSelf, address xPeer) private { uint256 feeForWorker; if(selfKind == SELF_KIND_SELLER){ feeForWorker = wei_item_trade(idItem, price, amountItemDone, xSelf, xPeer); }else{ feeForWorker = wei_item_trade(idItem, price, amountItemDone, xPeer, xSelf); } emit infoMatching(idItem, price, amountItemDone, xSelf, xPeer, feeForWorker); } event infoMatching(uint256 idItem, uint32 price, uint32 amountItemDone, address xSelf, address xPeer, uint256 feeForWorker); uint256 constant FEE_RATE = 1; // Fee rate : 1% function getFeeBase(uint256 amountWei) private pure returns(uint256 feeBase) { feeBase = (amountWei / 100) * FEE_RATE; } function wei_item_trade(uint256 idItem, uint32 price, uint32 amountItem, address xSeller, address xBuyer) private returns (uint256 feeForWorker){ // Item : xOnOrder > xBuyer s_onOrder.Item_SendTo(xBuyer, idItem, amountItem); // Wei : xOnOrder > xSeller, xAgree uint256 amountWei = amountItem * price; uint256 feeBase = getFeeBase(amountWei); s_balances[address(s_onOrder)] -= amountWei + feeBase; // Fee payment by Buyer s_balances[xSeller] += amountWei - feeBase; // Fee payment by Seller feeForWorker = feeBase + feeBase; s_balances[msg.sender] += feeForWorker; // Fee receipt for a matching worker } function wei_fromSenderToOnOrder(uint256 amountWei) private { // Wei : msg.sender > xOnOrder s_balances[msg.sender] -= amountWei; s_balances[address(s_onOrder)] += amountWei; } function wei_fromOnOrderToSender(uint256 amountWei) private { // Wei : xOnOrder > msg.sender s_balances[address(s_onOrder)] -= amountWei; s_balances[msg.sender] += amountWei; } function item_fromSenderToOnOrder(uint256 idItem, uint32 amountItem) private { // Item : msg.sender > xOnOrder setApprovalForAll(address(s_onOrder), true); s_onOrder.Item_RecvFrom(msg.sender, idItem, amountItem); } function item_fromOnOrderToSender(uint256 idItem, uint32 amountItem) private { // Item : xOnOrder > msg.sender s_onOrder.Item_SendTo(msg.sender, idItem, amountItem); } event InfoAddress(address target); event InfoUint(uint256 target); function ShowInfo() public { emit InfoAddress(address(s_onOrder)); emit InfoAddress(address(this)); } }
Item : msg.sender > xOnOrder
function item_fromSenderToOnOrder(uint256 idItem, uint32 amountItem) private { setApprovalForAll(address(s_onOrder), true); s_onOrder.Item_RecvFrom(msg.sender, idItem, amountItem); }
954,894
// SPDX-License-Identifier: Apache-2.0 // 人類の反撃はこれからだ。 // jinrui no hangeki wa kore kara da. // Source code heavily inspired from deployed contract instance of Azuki collection // https://etherscan.io/address/0xed5af388653567af2f388e6224dc7c4b3241c544#code // The source code in the github does not have some important features. // This is why we used directly the code from the deployed version. pragma solidity >=0.8.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./ERC721A.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; /// @title KomorebiNoSekai NFT collection /// @author 0xmanga-eth contract KomorebiNoSekai is Ownable, ERC721A, ReentrancyGuard, VRFConsumerBase { using SafeMath for uint256; uint256 public immutable maxPerAddressDuringMint; uint256 public immutable amountForDevs; address public constant AZUKI_ADDRESS = 0xED5AF388653567Af2F388E6224dC7C4b3241C544; string constant ERROR_NOT_ENOUGH_LINK = "not enough LINK"; // Furaribi (ふらり火, Furaribi) are the ghost of those murdered // in cold blood by an angry samurai. // They get their namesake from them wandering // aimlessly around the edges of lakes and rivers. uint8 public constant FURARIBI_SIDE = 1; // ナイト Naito (from english: "Knight") // ライト Raito (from english: "Light") // They fight against Furaribi spirits to protect humans. uint8 public constant NAITO_RAITO_SIDE = 2; struct SaleConfig { uint32 whitelistSaleStartTime; uint32 saleStartTime; uint64 mintlistPrice; uint64 price; } struct Gift { address collectionAddress; uint256[] ids; } // The sale configuration SaleConfig public saleConfig; // Whitelisted addresses mapping(address => uint8) public _allowList; // Whitelisted NFT collections address[] public _whitelistedCollections; // Per user assigned side mapping(address => uint8) private _side; // The winner NFT id uint256 public giftsWinnerTokenId; // The winner of the gifts address public giftsWinnerAddress; // The list of NFT gifts Gift[] public gifts; // The chainlink request id for VRF bytes32 selectRandomGiftWinnerRequestId; // Chainlink configuration address _vrfCoordinator; address _linkToken; bytes32 _vrfKeyHash; uint256 _vrfFee; constructor( uint256 maxBatchSize_, uint256 collectionSize_, uint256 amountForDevs_, address vrfCoordinator_, address linkToken_, bytes32 vrfKeyHash_, uint256 vrfFee_ ) ERC721A("Komorebi No Sekai", "KNS", maxBatchSize_, collectionSize_) VRFConsumerBase(vrfCoordinator_, linkToken_) { maxPerAddressDuringMint = maxBatchSize_; amountForDevs = amountForDevs_; _vrfCoordinator = vrfCoordinator_; _linkToken = linkToken_; _vrfKeyHash = vrfKeyHash_; _vrfFee = vrfFee_; } /// @notice Buy a quantity of NFTs during the whitelisted sale. /// @dev Throws if user is not whitelisted. function allowlistMint() external payable callerIsUser { uint256 price = uint256(saleConfig.mintlistPrice); uint256 whitelistSaleStartTime = uint256(saleConfig.whitelistSaleStartTime); assignSideIfNoSide(msg.sender); require(getCurrentTime() >= whitelistSaleStartTime, "allowlist sale has not begun yet"); require(price != 0, "allowlist sale has not begun yet"); require(isWhitelisted(msg.sender), "not eligible for allowlist mint"); require(totalSupply() + 1 <= collectionSize, "reached max supply"); if (_allowList[msg.sender] > 0) { _allowList[msg.sender]--; } _safeMint(msg.sender, 1); refundIfOver(price); } /// @notice Buy a quantity of NFTs during the public primary sale. /// @param quantity The number of items to mint. function saleMint(uint256 quantity) external payable callerIsUser { SaleConfig memory config = saleConfig; uint256 price = uint256(config.price); uint256 saleStartTime = uint256(config.saleStartTime); assignSideIfNoSide(msg.sender); require(isPublicSaleOn(price, saleStartTime), "public sale has not begun yet"); require(totalSupply() + quantity <= collectionSize, "reached max supply"); require(numberMinted(msg.sender) + quantity <= maxPerAddressDuringMint, "can not mint this many"); _safeMint(msg.sender, quantity); refundIfOver(price * quantity); } /// @notice Mint NFTs for dev team. /// @dev For marketing etc. function devMint(uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= amountForDevs, "too many already minted before dev mint"); require(quantity % maxBatchSize == 0, "can only mint a multiple of the maxBatchSize"); uint256 numChunks = quantity / maxBatchSize; for (uint256 i = 0; i < numChunks; i++) { _safeMint(msg.sender, maxBatchSize); } } /// @notice Refund the difference if user sent more than the specified price. /// @param price The correct price. function refundIfOver(uint256 price) private { require(msg.value >= price, "Need to send more ETH."); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } /// @notice Return whether or not the public sale is live. /// @param priceWei The price set in WEI. /// @param saleStartTime The start time set. /// @return true if public sale is live, false otherwise. function isPublicSaleOn(uint256 priceWei, uint256 saleStartTime) public view returns (bool) { return priceWei != 0 && getCurrentTime() >= saleStartTime; } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } /// @notice Add addresses to allow list. /// @param addresses The account addresses to whitelist. /// @param numAllowedToMint The number of allowed NFTs to mint per address. function setAllowList(address[] calldata addresses, uint8 numAllowedToMint) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { _allowList[addresses[i]] = numAllowedToMint; } } // // metadata URI string private _baseTokenURI; /// @notice Return the current base URI. /// @return The current base URI. function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /// @notice Set the base URI for the collection. /// @dev Can be used to handle a reveal separately. /// @param baseURI The new base URI. function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } /// @notice Withdraw ETH from the contract. /// @dev Only owner can call this function. function withdrawMoney() external onlyOwner nonReentrant { (bool success, ) = msg.sender.call{ value: address(this).balance }(""); require(success, "Transfer failed."); } /// @notice Return the number of minted NFTs for a given address. /// @param owner The address of the owner. /// @return The number of minted NFTs. function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } /// @notice Get ownership data. /// @param tokenId The token id. /// @return The `TokenOwnership` structure data associated to the token id. function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } /// @notice Return the current time. /// @dev Can be extended for testing purpose. /// @return The current timestamp. function getCurrentTime() internal view virtual returns (uint256) { return block.timestamp; } /// @notice Set whitelist sale start time. /// @param whitelistSaleStartTime_ The start time as a timestamp. function setWhitelistSaleStartTime(uint32 whitelistSaleStartTime_) external onlyOwner { SaleConfig storage config = saleConfig; config.whitelistSaleStartTime = whitelistSaleStartTime_; } /// @notice Set public sale start time. /// @param saleStartTime_ The start time as a timestamp. function setSaleStartTime(uint32 saleStartTime_) external onlyOwner { SaleConfig storage config = saleConfig; config.saleStartTime = saleStartTime_; } /// @notice Set current price for whitelisted sale. /// @param mintlistPrice_ The price in WEI. function setMintlistPrice(uint64 mintlistPrice_) external onlyOwner { SaleConfig storage config = saleConfig; config.mintlistPrice = mintlistPrice_; } /// @notice Set current price for public sale. /// @param price_ The price in WEI. function setPrice(uint64 price_) external onlyOwner { SaleConfig storage config = saleConfig; config.price = price_; } /// @notice Return the side of `msg.sender`. /// @return The side. function getMySide() public view returns (uint8) { return getSide(msg.sender); } /// @notice Return the side of a specified address. /// @return The side. function getSide(address account) public view returns (uint8) { return _side[account]; } /// @notice Return whether or not the specified address is assigned to a side. /// @return true if assigned, false otherwise. function hasSide(address account) public view returns (bool) { return _side[account] != 0; } /// @notice Assign a side to the specified address if not assigned yet. /// @param account The address to assign a side to. function assignSideIfNoSide(address account) internal { if (!hasSide(account)) { assignSide(account); } } /// @notice Assign a side to the specified address. /// @dev Throws if address has already a side assigned. /// @param account The address to assign a side to. function assignSide(address account) internal { require(!hasSide(account), "Account already assigned to a side"); uint8 side; uint256 seed = uint256(getSeed()); if (uint8(seed) % 2 == 0) { side = FURARIBI_SIDE; } else { side = NAITO_RAITO_SIDE; } _side[account] = side; } /// @notice Assign a side to `msg.sender` function assignMeASide() external { assignSideIfNoSide(msg.sender); } /// @notice Compute a new seed to serve for simple and non sensitive pseudo random use cases. /// @return The seed to use. function getSeed() internal view returns (bytes32) { return keccak256(abi.encodePacked(block.timestamp, block.basefee, gasleft(), msg.sender, totalSupply())); } /// @notice Whitelist holders of specific collection NFTs. /// @param collectionAddress The address of the collection. function whitelistHoldersOfCollection(address collectionAddress) external onlyOwner { _whitelistedCollections.push(collectionAddress); } /// @notice Whitelist holders of Azuki NFTs. function whitelistAzukiHolders() external onlyOwner { _whitelistedCollections.push(AZUKI_ADDRESS); } /// @notice Return whether or not the specified account is whitelisted. /// @param account The address to check. /// @return true if whitelisted, false otherwise. function isWhitelisted(address account) internal view returns (bool) { if (_allowList[account] > 0) { return true; } for (uint256 i = 0; i < _whitelistedCollections.length; i++) { IERC721 nftCollection = IERC721(_whitelistedCollections[i]); if (nftCollection.balanceOf(account) > 0) { return true; } } return false; } /// @notice Send NFT gifts to the selected winner. /// @dev Throws if the winner is not selected yet. function sendGiftsToWinner() external onlyIfWinnerSelected onlyOwner { for (uint256 i = 0; i < gifts.length; i++) { Gift memory gift = gifts[i]; IERC721 collection = IERC721(gift.collectionAddress); uint256[] memory ids = gift.ids; for (uint256 j = 0; j < ids.length; j++) { uint256 id = ids[j]; collection.safeTransferFrom(address(this), giftsWinnerAddress, id); } } } modifier onlyIfWinnerSelected() { require(giftsWinnerAddress != address(0x0), "winner must be selected"); _; } /// @notice Select a random winner using Chainlink VRF. function selectRandomWinnerForGifts() external onlyOwner requireFeeForLinkRequest { require(giftsWinnerAddress == address(0x0), "winner already selected"); selectRandomGiftWinnerRequestId = requestRandomness(_vrfKeyHash, _vrfFee); } /// @notice Withdraw Link /// @dev See chainlink documentation. function withdrawLink() external onlyOwner { IERC20 erc20 = IERC20(_linkToken); uint256 linkBalance = LINK.balanceOf(address(this)); if (linkBalance > 0) { erc20.transfer(owner(), linkBalance); } } modifier requireFeeForLinkRequest() { require(LINK.balanceOf(address(this)) >= _vrfFee, ERROR_NOT_ENOUGH_LINK); _; } /// @dev See `VRFConsumerBase` documentation. function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { if (requestId == selectRandomGiftWinnerRequestId && giftsWinnerAddress == address(0x0)) { giftsWinnerTokenId = randomness.mod(totalSupply()); giftsWinnerAddress = ownerOf(giftsWinnerTokenId); } } /// @notice Add gift to the list of gifts. /// @param collectionAddress Address of the NFT collection. /// @param ids The list of token ids. function addGift(address collectionAddress, uint256[] calldata ids) external { gifts.push(Gift(collectionAddress, ids)); } /// @notice Update VRF fee. function updateVRFFee(uint256 fee) external onlyOwner { _vrfFee = fee; } }
Return the side of a specified address. return The side.
function getSide(address account) public view returns (uint8) { return _side[account]; }
13,052,449
./partial_match/1/0x409bf77A8E3Fe384497227eA508029B5364933DE/sources/contracts/staking/TokenStaking.sol
Takes the given number of queued slashing operations and processes them. Receives 5% of the slashed amount. Executes `involuntaryAuthorizationDecrease` function on each affected application.
function processSlashing(uint256 count) external virtual override { require( slashingQueueIndex < slashingQueue.length && count > 0, "Nothing to process" ); uint256 maxIndex = slashingQueueIndex + count; maxIndex = MathUpgradeable.min(maxIndex, slashingQueue.length); count = maxIndex - slashingQueueIndex; uint96 tAmountToBurn = 0; uint256 index = slashingQueueIndex; for (; index < maxIndex; index++) { SlashingEvent storage slashing = slashingQueue[index]; tAmountToBurn += processSlashing(slashing); } slashingQueueIndex = index; uint256 tProcessorReward = uint256(tAmountToBurn).percent( SLASHING_REWARD_PERCENT ); notifiersTreasury += tAmountToBurn - tProcessorReward.toUint96(); emit SlashingProcessed(msg.sender, count, tProcessorReward); if (tProcessorReward > 0) { token.safeTransfer(msg.sender, tProcessorReward); } }
2,586,929
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondCut } from "./diamond/LibDiamondCut.sol"; import { DiamondFacet } from "./diamond/DiamondFacet.sol"; import { OwnershipFacet } from "./diamond/OwnershipFacet.sol"; import { LibDiamondStorage } from "./diamond/LibDiamondStorage.sol"; import { IDiamondCut } from "./diamond/IDiamondCut.sol"; import { IDiamondLoupe } from "./diamond/IDiamondLoupe.sol"; import { IERC165 } from "./diamond/IERC165.sol"; import { LibDiamondStorageDerivaDEX } from "./storage/LibDiamondStorageDerivaDEX.sol"; import { IDDX } from "./tokens/interfaces/IDDX.sol"; /** * @title DerivaDEX * @author DerivaDEX * @notice This is the diamond for DerivaDEX. All current * and future logic runs by way of this contract. * @dev This diamond implements the Diamond Standard (EIP #2535). */ contract DerivaDEX { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This constructor initializes the upgrade machinery (as * per the Diamond Standard), sets the admin of the proxy * to be the deploying address (very temporary), and sets * the native DDX governance/operational token. * @param _ddxToken The native DDX token address. */ constructor(IDDX _ddxToken) public { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Temporarily set admin to the deploying address to facilitate // adding the Diamond functions dsDerivaDEX.admin = msg.sender; // Set DDX token address for token logic in facet contracts require(address(_ddxToken) != address(0), "DerivaDEX: ddx token is zero address."); dsDerivaDEX.ddxToken = _ddxToken; emit OwnershipTransferred(address(0), msg.sender); // Create DiamondFacet contract - // implements DiamondCut interface and DiamondLoupe interface DiamondFacet diamondFacet = new DiamondFacet(); // Create OwnershipFacet contract which implements ownership // functions and supportsInterface function OwnershipFacet ownershipFacet = new OwnershipFacet(); IDiamondCut.FacetCut[] memory diamondCut = new IDiamondCut.FacetCut[](2); // adding diamondCut function and diamond loupe functions diamondCut[0].facetAddress = address(diamondFacet); diamondCut[0].action = IDiamondCut.FacetCutAction.Add; diamondCut[0].functionSelectors = new bytes4[](6); diamondCut[0].functionSelectors[0] = DiamondFacet.diamondCut.selector; diamondCut[0].functionSelectors[1] = DiamondFacet.facetFunctionSelectors.selector; diamondCut[0].functionSelectors[2] = DiamondFacet.facets.selector; diamondCut[0].functionSelectors[3] = DiamondFacet.facetAddress.selector; diamondCut[0].functionSelectors[4] = DiamondFacet.facetAddresses.selector; diamondCut[0].functionSelectors[5] = DiamondFacet.supportsInterface.selector; // adding ownership functions diamondCut[1].facetAddress = address(ownershipFacet); diamondCut[1].action = IDiamondCut.FacetCutAction.Add; diamondCut[1].functionSelectors = new bytes4[](2); diamondCut[1].functionSelectors[0] = OwnershipFacet.transferOwnershipToSelf.selector; diamondCut[1].functionSelectors[1] = OwnershipFacet.getAdmin.selector; // execute internal diamondCut function to add functions LibDiamondCut.diamondCut(diamondCut, address(0), new bytes(0)); // adding ERC165 data ds.supportedInterfaces[IERC165.supportsInterface.selector] = true; ds.supportedInterfaces[IDiamondCut.diamondCut.selector] = true; bytes4 interfaceID = IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector; ds.supportedInterfaces[interfaceID] = true; } // TODO(jalextowle): Remove this linter directive when // https://github.com/protofire/solhint/issues/248 is merged and released. /* solhint-disable ordering */ receive() external payable { revert("DerivaDEX does not directly accept ether."); } // Finds facet for function that is called and executes the // function if it is found and returns any value. fallback() external payable { LibDiamondStorage.DiamondStorage storage ds; bytes32 position = LibDiamondStorage.DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress; require(facet != address(0), "Function does not exist."); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(0, 0, size) switch result case 0 { revert(0, size) } default { return(0, size) } } } /* solhint-enable ordering */ } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of internal diamondCut function. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./IDiamondCut.sol"; library LibDiamondCut { event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'FacetCut[] memory _diamondCut' instead of // 'FacetCut[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { require(_diamondCut.length > 0, "LibDiamondCut: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); // add or replace functions if (_newFacetAddress != address(0)) { uint256 facetAddressPosition = ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition; // add new facet address if it does not exist if ( facetAddressPosition == 0 && ds.facetFunctionSelectors[_newFacetAddress].functionSelectors.length == 0 ) { ensureHasContractCode(_newFacetAddress, "LibDiamondCut: New facet has no code"); facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_newFacetAddress); ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } // add or replace selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; // add if (_action == IDiamondCut.FacetCutAction.Add) { require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addSelector(_newFacetAddress, selector); } else if (_action == IDiamondCut.FacetCutAction.Replace) { // replace require( oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function" ); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } } else { require( _action == IDiamondCut.FacetCutAction.Remove, "LibDiamondCut: action not set to FacetCutAction.Remove" ); // remove selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; removeSelector(ds.selectorToFacetAndPosition[selector].facetAddress, selector); } } } function addSelector(address _newFacet, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 selectorPosition = ds.facetFunctionSelectors[_newFacet].functionSelectors.length; ds.facetFunctionSelectors[_newFacet].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _newFacet; ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = uint16(selectorPosition); } function removeSelector(address _oldFacetAddress, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_oldFacetAddress != address(0), "LibDiamondCut: Can't remove or replace function that doesn't exist"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.length - 1; bytes4 lastSelector = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[lastSelectorPosition]; // if not the same then replace _selector with lastSelector if (lastSelector != _selector) { ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; uint256 facetAddressPosition = ds.facetFunctionSelectors[_oldFacetAddress].facetAddressPosition; if (_oldFacetAddress != lastFacetAddress) { ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_oldFacetAddress]; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { LibDiamondCut.ensureHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function ensureHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of diamondCut external function and DiamondLoupe interface. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./LibDiamondCut.sol"; import "../storage/LibDiamondStorageDerivaDEX.sol"; import "./IDiamondCut.sol"; import "./IDiamondLoupe.sol"; import "./IERC165.sol"; contract DiamondFacet is IDiamondCut, IDiamondLoupe, IERC165 { // Standard diamondCut external function /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "DiamondFacet: Must own the contract"); require(_diamondCut.length > 0, "DiamondFacet: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { LibDiamondCut.addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); LibDiamondCut.initializeDiamondCut(_init, _calldata); } // Diamond Loupe Functions //////////////////////////////////////////////////////////////////// /// These functions are expected to be called frequently by tools. // // struct Facet { // address facetAddress; // bytes4[] functionSelectors; // } // /// @notice Gets all facets and their selectors. /// @return facets_ Facet function facets() external view override returns (Facet[] memory facets_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 numFacets = ds.facetAddresses.length; facets_ = new Facet[](numFacets); for (uint256 i; i < numFacets; i++) { address facetAddress_ = ds.facetAddresses[i]; facets_[i].facetAddress = facetAddress_; facets_[i].functionSelectors = ds.facetFunctionSelectors[facetAddress_].functionSelectors; } } /// @notice Gets all the function selectors provided by a facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view override returns (bytes4[] memory facetFunctionSelectors_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetFunctionSelectors_ = ds.facetFunctionSelectors[_facet].functionSelectors; } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view override returns (address[] memory facetAddresses_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddresses_ = ds.facetAddresses; } /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddress_ = ds.selectorToFacetAndPosition[_functionSelector].facetAddress; } // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external view override returns (bool) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { LibDiamondStorageDerivaDEX } from "../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorage } from "../diamond/LibDiamondStorage.sol"; import { IERC165 } from "./IERC165.sol"; contract OwnershipFacet { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This function transfers ownership to self. This is done * so that we can ensure upgrades (using diamondCut) and * various other critical parameter changing scenarios * can only be done via governance (a facet). */ function transferOwnershipToSelf() external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Not authorized"); dsDerivaDEX.admin = address(this); emit OwnershipTransferred(msg.sender, address(this)); } /** * @notice This gets the admin for the diamond. * @return Admin address. */ function getAdmin() external view returns (address) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); return dsDerivaDEX.admin; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ library LibDiamondStorage { struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the facet address in the facetAddresses array // and the position of the selector in the facetSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; } bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ interface IDiamondCut { enum FacetCutAction { Add, Replace, Remove } struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ import "./IDiamondCut.sol"; // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IERC165 { /// @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); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "../tokens/interfaces/IDDX.sol"; library LibDiamondStorageDerivaDEX { struct DiamondStorageDerivaDEX { string name; address admin; IDDX ddxToken; } bytes32 constant DIAMOND_STORAGE_POSITION_DERIVADEX = keccak256("diamond.standard.diamond.storage.DerivaDEX.DerivaDEX"); function diamondStorageDerivaDEX() internal pure returns (DiamondStorageDerivaDEX storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_DERIVADEX; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IDDX { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "./interfaces/IDDX.sol"; /** * @title DDXWalletCloneable * @author DerivaDEX * @notice This is a cloneable on-chain DDX wallet that holds a trader's * stakes and issued rewards. */ contract DDXWalletCloneable { // Whether contract has already been initialized once before bool initialized; /** * @notice This function initializes the on-chain DDX wallet * for a given trader. * @param _trader Trader address. * @param _ddxToken DDX token address. * @param _derivaDEX DerivaDEX Proxy address. */ function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external { // Prevent initializing more than once require(!initialized, "DDXWalletCloneable: already init."); initialized = true; // Automatically delegate the holdings of this contract/wallet // back to the trader. _ddxToken.delegate(_trader); // Approve the DerivaDEX Proxy contract for unlimited transfers _ddxToken.approve(_derivaDEX, uint96(-1)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { DDXWalletCloneable } from "../../tokens/DDXWalletCloneable.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; import { LibTraderInternal } from "./LibTraderInternal.sol"; /** * @title Trader * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to traders - staking DDX, withdrawing * DDX, receiving DDX rewards, etc. */ contract Trader { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event RewardCliffSet(bool rewardCliffSet); event DDXRewardIssued(address trader, uint96 amount); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Trader: must be called by Gov."); _; } /** * @notice Limits functions to only be called post reward cliff. */ modifier postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); require(dsTrader.rewardCliff, "Trader: prior to reward cliff."); _; } /** * @notice This function initializes the state with some critical * information, including the on-chain wallet cloneable * contract address. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. */ function initialize(IDDXWalletCloneable _ddxWalletCloneable) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the on-chain DDX wallet cloneable contract address dsTrader.ddxWalletCloneable = _ddxWalletCloneable; } /** * @notice This function sets the reward cliff. * @param _rewardCliff Reward cliff. */ function setRewardCliff(bool _rewardCliff) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the reward cliff (boolean value) dsTrader.rewardCliff = _rewardCliff; emit RewardCliffSet(_rewardCliff); } /** * @notice This function issues DDX rewards to a trader. It can * only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _trader Trader recipient address. */ function issueDDXReward(uint96 _amount, address _trader) external onlyAdmin { // Call the internal function to issue DDX rewards. This // internal function is shareable with other facets that import // the LibTraderInternal library. LibTraderInternal.issueDDXReward(_amount, _trader); } /** * @notice This function issues DDX rewards to an external address. * It can only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _recipient External recipient address. */ function issueDDXToRecipient(uint96 _amount, address _recipient) external onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(_recipient, _amount); emit DDXRewardIssued(_recipient, _amount); } /** * @notice This function lets traders take DDX from their wallet * into their on-chain DDX wallet. It's important to note * that any DDX staked from the trader to this wallet * delegates the voting rights of that stake back to the * user. To be more explicit, if Alice's personal wallet is * delegating to Bob, and she now stakes a portion of her * DDX into this on-chain DDX wallet of hers, those tokens * will now count towards her voting power, not Bob's, since * her on-chain wallet is automatically delegating back to * her. * @param _amount The DDX tokens to be staked. */ function stakeDDXFromTrader(uint96 _amount) external { transferDDXToWallet(msg.sender, _amount); } /** * @notice This function lets traders send DDX from their wallet * into another trader's on-chain DDX wallet. It's * important to note that any DDX staked to this wallet * delegates the voting rights of that stake back to the * user. * @param _trader Trader address to receive DDX (inside their * wallet, which will be created if it does not already * exist). * @param _amount The DDX tokens to be staked. */ function sendDDXFromTraderToTraderWallet(address _trader, uint96 _amount) external { transferDDXToWallet(_trader, _amount); } /** * @notice This function lets traders withdraw DDX from their * on-chain DDX wallet to their personal wallet. It's * important to note that the voting rights for any DDX * withdrawn are returned back to the delegatee of the * user's personal wallet. To be more explicit, if Alice is * personal wallet is delegating to Bob, and she now * withdraws a portion of her DDX from this on-chain DDX * wallet of hers, those tokens will now count towards Bob's * voting power, not her's, since her on-chain wallet is * automatically delegating back to her, but her personal * wallet is delegating to Bob. Withdrawals can only happen * when the governance cliff is lifted. * @param _amount The DDX tokens to be withdrawn. */ function withdrawDDXToTrader(uint96 _amount) external postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[msg.sender]; LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Subtract trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.sub96(_amount); // Transfer DDX from trader's on-chain wallet to the trader dsDerivaDEX.ddxToken.transferFrom(trader.ddxWalletContract, msg.sender, _amount); } /** * @notice This function gets the attributes for a given trader. * @param _trader Trader address. */ function getTrader(address _trader) external view returns (TraderDefs.Trader memory) { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); return dsTrader.traders[_trader]; } /** * @notice This function transfers DDX from the sender * to another trader's DDX wallet. * @param _trader Trader address' DDX wallet address to transfer * into. * @param _amount Amount of DDX to transfer. */ function transferDDXToWallet(address _trader, uint96 _amount) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { LibTraderInternal.createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.transferFrom(msg.sender, trader.ddxWalletContract, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 SafeMath96 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add96(uint96 a, uint96 b) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub96(uint96 a, uint96 b) internal pure returns (uint96) { return sub96(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 sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); uint96 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title TraderDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * traders. */ library TraderDefs { // Consists of trader attributes, including the DDX balance and // the onchain DDX wallet contract address struct Trader { uint96 ddxBalance; address ddxWalletContract; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { TraderDefs } from "../libs/defs/TraderDefs.sol"; import { IDDXWalletCloneable } from "../tokens/interfaces/IDDXWalletCloneable.sol"; library LibDiamondStorageTrader { struct DiamondStorageTrader { mapping(address => TraderDefs.Trader) traders; bool rewardCliff; IDDXWalletCloneable ddxWalletCloneable; } bytes32 constant DIAMOND_STORAGE_POSITION_TRADER = keccak256("diamond.standard.diamond.storage.DerivaDEX.Trader"); function diamondStorageTrader() internal pure returns (DiamondStorageTrader storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_TRADER; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { IDDX } from "./IDDX.sol"; interface IDDXWalletCloneable { function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { LibClone } from "../../libs/LibClone.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; /** * @title TraderInternalLib * @author DerivaDEX * @notice This is a library of internal functions mainly defined in * the Trader facet, but used in other facets. */ library LibTraderInternal { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event DDXRewardIssued(address trader, uint96 amount); /** * @notice This function creates a new DDX wallet for a trader. * @param _trader Trader address. */ function createDDXWallet(address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Leveraging the minimal proxy contract/clone factory pattern // as described here (https://eips.ethereum.org/EIPS/eip-1167) IDDXWalletCloneable ddxWallet = IDDXWalletCloneable(LibClone.createClone(address(dsTrader.ddxWalletCloneable))); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Cloneable contracts have no constructor, so instead we use // an initialize function. This initialize delegates this // on-chain DDX wallet back to the trader and sets the allowance // for the DerivaDEX Proxy contract to be unlimited. ddxWallet.initialize(_trader, dsDerivaDEX.ddxToken, address(this)); // Store the on-chain wallet address in the trader's storage dsTrader.traders[_trader].ddxWalletContract = address(ddxWallet); } /** * @notice This function issues DDX rewards to a trader. It can be * called by any facet part of the diamond. * @param _amount DDX tokens to be rewarded. * @param _trader Trader address. */ function issueDDXReward(uint96 _amount, address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(trader.ddxWalletContract, _amount); emit DDXRewardIssued(_trader, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly library LibClone { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))) } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { InsuranceFundDefs } from "../../libs/defs/InsuranceFundDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageInsuranceFund } from "../../storage/LibDiamondStorageInsuranceFund.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { LibTraderInternal } from "../trader/LibTraderInternal.sol"; import { IAToken } from "../interfaces/IAToken.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICToken } from "../interfaces/ICToken.sol"; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; import { IDIFundTokenFactory } from "../../tokens/interfaces/IDIFundTokenFactory.sol"; interface IERCCustom { function decimals() external view returns (uint8); } /** * @title InsuranceFund * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to insurance mining - staking directly * into the insurance fund and receiving a DDX issuance to be * used in governance/operations. * @dev This facet at the moment only handles insurance mining. It can * and will grow to handle the remaining functions of the insurance * fund, such as receiving quote-denominated fees and liquidation * spreads, among others. The Diamond storage will only be * affected when facet functions are called via the proxy * contract, no checks are necessary. */ contract InsuranceFund { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath for uint96; using SafeMath for uint256; using MathHelpers for uint32; using MathHelpers for uint96; using MathHelpers for uint224; using MathHelpers for uint256; using SafeERC20 for IERC20; // Compound-related constant variables // kovan: 0x5eAe89DC1C671724A672ff0630122ee834098657 IComptroller public constant COMPTROLLER = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); // kovan: 0x61460874a7196d6a22D1eE4922473664b3E95270 IERC20 public constant COMP_TOKEN = IERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); event InsuranceFundInitialized( uint32 interval, uint32 withdrawalFactor, uint96 mineRatePerBlock, uint96 advanceIntervalReward, uint256 miningFinalBlockNumber ); event InsuranceFundCollateralAdded( bytes32 collateralName, address underlyingToken, address collateralToken, InsuranceFundDefs.Flavor flavor ); event StakedToInsuranceFund(address staker, uint96 amount, bytes32 collateralName); event WithdrawnFromInsuranceFund(address withdrawer, uint96 amount, bytes32 collateralName); event AdvancedOtherRewards(address intervalAdvancer, uint96 advanceReward); event InsuranceMineRewardsClaimed(address claimant, uint96 minedAmount); event MineRatePerBlockSet(uint96 mineRatePerBlock); event AdvanceIntervalRewardSet(uint96 advanceIntervalReward); event WithdrawalFactorSet(uint32 withdrawalFactor); event InsuranceMiningExtended(uint256 miningFinalBlockNumber); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "IFund: must be called by Gov."); _; } /** * @notice Limits functions to only be called while insurance * mining is ongoing. */ modifier insuranceMiningOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(block.number < dsInsuranceFund.miningFinalBlockNumber, "IFund: mining ended."); _; } /** * @notice Limits functions to only be called while other * rewards checkpointing is ongoing. */ modifier otherRewardsOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require( dsInsuranceFund.otherRewardsCheckpointBlock < dsInsuranceFund.miningFinalBlockNumber, "IFund: other rewards checkpointing ended." ); _; } /** * @notice Limits functions to only be called via governance. */ modifier isNotPaused { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); require(!dsPause.isPaused, "IFund: paused."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _interval The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @param _withdrawalFactor Specifies the withdrawal fee if users * redeem their insurance tokens. * @param _mineRatePerBlock The DDX tokens to be mined each interval * for insurance mining. * @param _advanceIntervalReward DDX reward for participant who * advances the insurance mining interval. * @param _insuranceMiningLength Insurance mining length (blocks). */ function initialize( uint32 _interval, uint32 _withdrawalFactor, uint96 _mineRatePerBlock, uint96 _advanceIntervalReward, uint256 _insuranceMiningLength, IDIFundTokenFactory _diFundTokenFactory ) external onlyAdmin { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) dsInsuranceFund.interval = _interval; // Keep track of the block number for other rewards checkpoint, // which is initialized to the block number the insurance fund // facet is added to the diamond dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Set the withdrawal factor, capped at 1000, implying 0% fee require(_withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); // Set withdrawal ratio, which will be used with a 1e3 scaling // factor, meaning a value of 995 implies a withdrawal fee of // 0.5% since 995/1e3 => 0.995 dsInsuranceFund.withdrawalFactor = _withdrawalFactor; // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; // Incentive to advance the other rewards interval // (e.g. 100e18 = 100 DDX) dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; // Set the final block number for insurance mining dsInsuranceFund.miningFinalBlockNumber = block.number.add(_insuranceMiningLength); // DIFundToken factory to deploy DerivaDEX Insurance Fund token // contracts pertaining to each supported collateral dsInsuranceFund.diFundTokenFactory = _diFundTokenFactory; // Initialize the DDX market state index and block. These values // are critical for computing the DDX continuously issued per // block dsInsuranceFund.ddxMarketState.index = 1e36; dsInsuranceFund.ddxMarketState.block = block.number.safe32("IFund: exceeds 32 bits"); emit InsuranceFundInitialized( _interval, _withdrawalFactor, _mineRatePerBlock, _advanceIntervalReward, dsInsuranceFund.miningFinalBlockNumber ); } /** * @notice This function sets the DDX mine rate per block. * @param _mineRatePerBlock The DDX tokens mine rate per block. */ function setMineRatePerBlock(uint96 _mineRatePerBlock) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // NOTE(jalextowle): We must update the DDX Market State prior to // changing the mine rate per block in order to lock in earned rewards // for insurance mining participants. updateDDXMarketState(dsInsuranceFund); require(_mineRatePerBlock != dsInsuranceFund.mineRatePerBlock, "IFund: same as current value."); // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; emit MineRatePerBlockSet(_mineRatePerBlock); } /** * @notice This function sets the advance interval reward. * @param _advanceIntervalReward DDX reward for advancing interval. */ function setAdvanceIntervalReward(uint96 _advanceIntervalReward) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_advanceIntervalReward != dsInsuranceFund.advanceIntervalReward, "IFund: same as current value."); // Set the advance interval reward dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; emit AdvanceIntervalRewardSet(_advanceIntervalReward); } /** * @notice This function sets the withdrawal factor. * @param _withdrawalFactor Withdrawal factor. */ function setWithdrawalFactor(uint32 _withdrawalFactor) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_withdrawalFactor != dsInsuranceFund.withdrawalFactor, "IFund: same as current value."); // Set the withdrawal factor, capped at 1000, implying 0% fee require(dsInsuranceFund.withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); dsInsuranceFund.withdrawalFactor = _withdrawalFactor; emit WithdrawalFactorSet(_withdrawalFactor); } /** * @notice This function extends insurance mining. * @param _insuranceMiningExtension Insurance mining extension * (blocks). */ function extendInsuranceMining(uint256 _insuranceMiningExtension) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_insuranceMiningExtension != 0, "IFund: invalid extension."); // Extend the mining final block number dsInsuranceFund.miningFinalBlockNumber = dsInsuranceFund.miningFinalBlockNumber.add(_insuranceMiningExtension); emit InsuranceMiningExtended(dsInsuranceFund.miningFinalBlockNumber); } /** * @notice This function adds a new supported collateral type that * can be staked to the insurance fund. It can only * be called via governance. * @dev For vanilla contracts (e.g. USDT, USDC, etc.), the * underlying token equals address(0). * @param _collateralName Name of collateral. * @param _collateralSymbol Symbol of collateral. * @param _underlyingToken Deployed address of underlying token. * @param _collateralToken Deployed address of collateral token. * @param _flavor Collateral flavor (Vanilla, Compound, Aave, etc.). */ function addInsuranceFundCollateral( string memory _collateralName, string memory _collateralSymbol, address _underlyingToken, address _collateralToken, InsuranceFundDefs.Flavor _flavor ) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain bytes32 representation of collateral name bytes32 result; assembly { result := mload(add(_collateralName, 32)) } // Ensure collateral has not already been added require( dsInsuranceFund.stakeCollaterals[result].collateralToken == address(0), "IFund: collateral already added." ); require(_collateralToken != address(0), "IFund: collateral address must be non-zero."); require(!isCollateralTokenPresent(_collateralToken), "IFund: collateral token already present."); require(_underlyingToken != _collateralToken, "IFund: token addresses are same."); if (_flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of vanilla flavor, there should only be // a value for collateral token, and underlying token should // be empty require(_underlyingToken == address(0), "IFund: underlying address non-zero for Vanilla."); } // Add collateral type to storage, including its underlying // token and collateral token addresses, and its flavor dsInsuranceFund.stakeCollaterals[result].underlyingToken = _underlyingToken; dsInsuranceFund.stakeCollaterals[result].collateralToken = _collateralToken; dsInsuranceFund.stakeCollaterals[result].flavor = _flavor; // Create a DerivaDEX Insurance Fund token contract associated // with this supported collateral dsInsuranceFund.stakeCollaterals[result].diFundToken = IDIFundToken( dsInsuranceFund.diFundTokenFactory.createNewDIFundToken( _collateralName, _collateralSymbol, IERCCustom(_collateralToken).decimals() ) ); dsInsuranceFund.collateralNames.push(result); emit InsuranceFundCollateralAdded(result, _underlyingToken, _collateralToken, _flavor); } /** * @notice This function allows participants to stake a supported * collateral type to the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function stakeToInsuranceFund(bytes32 _collateralName, uint96 _amount) external insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero stake amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for staking user. We do this prior to the stake // taking effect, thereby preventing someone from being rewarded // instantly for the stake. claimDDXFromInsuranceMining(msg.sender); // Increment the underlying capitalization stakeCollateral.cap = stakeCollateral.cap.add96(_amount); // Transfer collateral amount from user to proxy contract IERC20(stakeCollateral.collateralToken).safeTransferFrom(msg.sender, address(this), _amount); // Mint DIFund tokens to user stakeCollateral.diFundToken.mint(msg.sender, _amount); emit StakedToInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice This function allows participants to withdraw a supported * collateral type from the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function withdrawFromInsuranceFund(bytes32 _collateralName, uint96 _amount) external isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero withdraw amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for withdrawing user. We do this prior to the // redeem taking effect. claimDDXFromInsuranceMining(msg.sender); // Determine underlying to transfer based on how much underlying // can be redeemed given the current underlying capitalization // and how many DIFund tokens are globally available. This // theoretically fails in the scenario where globally there are // 0 insurance fund tokens, however that would mean the user // also has 0 tokens in their possession, and thus would have // nothing to be redeemed anyways. uint96 underlyingToTransferNoFee = _amount.proportion96(stakeCollateral.cap, stakeCollateral.diFundToken.totalSupply()); uint96 underlyingToTransfer = underlyingToTransferNoFee.proportion96(dsInsuranceFund.withdrawalFactor, 1e3); // Decrement the capitalization stakeCollateral.cap = stakeCollateral.cap.sub96(underlyingToTransferNoFee); // Increment the withdrawal fee cap stakeCollateral.withdrawalFeeCap = stakeCollateral.withdrawalFeeCap.add96( underlyingToTransferNoFee.sub96(underlyingToTransfer) ); // Transfer collateral amount from proxy contract to user IERC20(stakeCollateral.collateralToken).safeTransfer(msg.sender, underlyingToTransfer); // Burn DIFund tokens being redeemed from user stakeCollateral.diFundToken.burnFrom(msg.sender, _amount); emit WithdrawnFromInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice Advance other rewards interval */ function advanceOtherRewardsInterval() external otherRewardsOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Check if the current block has exceeded the interval bounds, // allowing for a new other rewards interval to be checkpointed require( block.number >= dsInsuranceFund.otherRewardsCheckpointBlock.add(dsInsuranceFund.interval), "IFund: advance too soon." ); // Maintain the USD-denominated sum of all Compound-flavor // assets. This needs to be stored separately than the rest // due to the way COMP tokens are rewarded to the contract in // order to properly disseminate to the user. uint96 normalizedCapCheckpointSumCompound; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, set the exchange // rate at this point in time. We do this so later on, // when claiming rewards, we know the exchange rate // checkpointed balances should be converted to // determine the USD-denominated value of holdings // needed to compute fair share of DDX rewards. stakeCollateral.exchangeRate = ICToken(stakeCollateral.collateralToken).exchangeRateStored().safe96( "IFund: amount exceeds 96 bits" ); // Set checkpoint cap for this Compound flavor // collateral to handle COMP distribution lookbacks stakeCollateral.checkpointCap = stakeCollateral.cap; // Increment the normalized Compound checkpoint cap // with the USD-denominated value normalizedCapCheckpointSumCompound = normalizedCapCheckpointSumCompound.add96( getUnderlyingTokenAmountForCompound(stakeCollateral.cap, stakeCollateral.exchangeRate) ); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // If collateral is of type Aave, we need to do some // custom Aave aToken reward distribution. We first // determine the contract's aToken balance for this // collateral type and subtract the underlying // aToken capitalization that are due to users. This // leaves us with the excess that has been rewarded // to the contract due to Aave's mechanisms, but // belong to the users. uint96 myATokenBalance = uint96(IAToken(stakeCollateral.collateralToken).balanceOf(address(this)).sub(stakeCollateral.cap)); // Store the aToken yield information dsInsuranceFund.aTokenYields[dsInsuranceFund.collateralNames[i]] = InsuranceFundDefs .ExternalYieldCheckpoint({ accrued: myATokenBalance, totalNormalizedCap: 0 }); } } // Ensure that the normalized cap sum is non-zero if (normalizedCapCheckpointSumCompound > 0) { // If there's Compound-type asset capitalization in the // system, claim COMP accrued to this contract. This COMP is // a result of holding all the cToken deposits from users. // We claim COMP via Compound's Comptroller contract. COMPTROLLER.claimComp(address(this)); // Obtain contract's balance of COMP uint96 myCompBalance = COMP_TOKEN.balanceOf(address(this)).safe96("IFund: amount exceeds 96 bits."); // Store the updated value as the checkpointed COMP yield owed // for this interval dsInsuranceFund.compYields = InsuranceFundDefs.ExternalYieldCheckpoint({ accrued: myCompBalance, totalNormalizedCap: normalizedCapCheckpointSumCompound }); } // Set other rewards checkpoint block to current block dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Issue DDX reward to trader's on-chain DDX wallet as an // incentive to users calling this function LibTraderInternal.issueDDXReward(dsInsuranceFund.advanceIntervalReward, msg.sender); emit AdvancedOtherRewards(msg.sender, dsInsuranceFund.advanceIntervalReward); } /** * @notice This function gets some high level insurance mining * details. * @return The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @return Current insurance mine withdrawal factor. * @return DDX reward for advancing interval. * @return Total global insurance mined amount in DDX. * @return Current insurance mine rate per block. * @return Insurance mining final block number. * @return DDX market state used for continuous DDX payouts. * @return Supported collateral names supported. */ function getInsuranceMineInfo() external view returns ( uint32, uint32, uint96, uint96, uint96, uint256, InsuranceFundDefs.DDXMarketState memory, bytes32[] memory ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return ( dsInsuranceFund.interval, dsInsuranceFund.withdrawalFactor, dsInsuranceFund.advanceIntervalReward, dsInsuranceFund.minedAmount, dsInsuranceFund.mineRatePerBlock, dsInsuranceFund.miningFinalBlockNumber, dsInsuranceFund.ddxMarketState, dsInsuranceFund.collateralNames ); } /** * @notice This function gets the current claimant state for a user. * @param _claimant Claimant address. * @return Claimant state. */ function getDDXClaimantState(address _claimant) external view returns (InsuranceFundDefs.DDXClaimantState memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.ddxClaimantState[_claimant]; } /** * @notice This function gets a supported collateral type's data, * including collateral's token addresses, collateral * flavor/type, current cap and withdrawal amounts, the * latest checkpointed cap, and exchange rate (for cTokens). * An interface for the DerivaDEX Insurance Fund token * corresponding to this collateral is also maintained. * @param _collateralName Name of collateral. * @return Stake collateral. */ function getStakeCollateralByCollateralName(bytes32 _collateralName) external view returns (InsuranceFundDefs.StakeCollateral memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.stakeCollaterals[_collateralName]; } /** * @notice This function gets unclaimed DDX rewards for a claimant. * @param _claimant Claimant address. * @return Unclaimed DDX rewards. */ function getUnclaimedDDXRewards(address _claimant) external view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 deltaBlocks = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber).sub(dsInsuranceFund.ddxMarketState.block); // Save off last index value uint256 index = dsInsuranceFund.ddxMarketState.index; // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index index = index.add(ratio); } // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (index > 0)) { ddxClaimantIndex = 1e36; } // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the unclaimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above return claimantTokens.mul(index.sub(ddxClaimantIndex)).div(1e36).safe96("IFund: exceeds 96 bits"); } /** * @notice Calculate DDX accrued by a claimant and possibly transfer * it to them. * @param _claimant The address of the claimant. */ function claimDDXFromInsuranceMining(address _claimant) public { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Update the DDX Market State in order to determine the amount of // rewards that should be paid to the claimant. updateDDXMarketState(dsInsuranceFund); // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; dsInsuranceFund.ddxClaimantState[_claimant].index = dsInsuranceFund.ddxMarketState.index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (dsInsuranceFund.ddxMarketState.index > 0)) { ddxClaimantIndex = 1e36; } // Compute the difference between the latest DDX market state // index and the claimant's index uint256 deltaIndex = uint256(dsInsuranceFund.ddxMarketState.index).sub(ddxClaimantIndex); // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the claimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above uint96 claimantDelta = claimantTokens.mul(deltaIndex).div(1e36).safe96("IFund: exceeds 96 bits"); if (claimantDelta != 0) { // Adjust insurance mined amount dsInsuranceFund.minedAmount = dsInsuranceFund.minedAmount.add96(claimantDelta); // Increment the insurance mined claimed DDX for claimant dsInsuranceFund.ddxClaimantState[_claimant].claimedDDX = dsInsuranceFund.ddxClaimantState[_claimant] .claimedDDX .add96(claimantDelta); // Mint the DDX governance/operational token claimed reward // from the proxy contract to the participant LibTraderInternal.issueDDXReward(claimantDelta, _claimant); } // Check if COMP or aTokens have not already been claimed if (dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] < dsInsuranceFund.otherRewardsCheckpointBlock) { // Record the current block number preventing a user from // reclaiming the COMP reward unfairly dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] = block.number; // Claim COMP and extra aTokens claimOtherRewardsFromInsuranceMining(_claimant); } emit InsuranceMineRewardsClaimed(_claimant, claimantDelta); } /** * @notice Get USDT-normalized collateral token amount. * @param _collateralName The collateral name. * @param _value The number of tokens. */ function getNormalizedCollateralValue(bytes32 _collateralName, uint96 _value) public view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; return (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(_value, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( _value, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); } /** * @notice This function gets a participant's current * USD-normalized/denominated stake and global * USD-normalized/denominated stake across all supported * collateral types. * @param _staker Participant's address. * @return Current USD redemption value of DIFund tokens staked. * @return Current USD global cap. */ function getCurrentTotalStakes(address _staker) public view returns (uint96, uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain running totals uint96 normalizedStakerStakeSum; uint96 normalizedGlobalCapSum; // Loop through each supported collateral for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { (, , uint96 normalizedStakerStake, uint96 normalizedGlobalCap) = getCurrentStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _staker); normalizedStakerStakeSum = normalizedStakerStakeSum.add96(normalizedStakerStake); normalizedGlobalCapSum = normalizedGlobalCapSum.add96(normalizedGlobalCap); } return (normalizedStakerStakeSum, normalizedGlobalCapSum); } /** * @notice This function gets a participant's current DIFund token * holdings and global DIFund token holdings for a * collateral type and staker, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getCurrentStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker uint96 stakerStake = stakeCollateral.diFundToken.balanceOf(_staker).safe96("IFund: exceeds 96 bits."); // Get DIFund tokens globally uint96 globalCap = stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits."); // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(stakeCollateral.cap, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( stakeCollateral.cap, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice This function gets a participant's DIFund token * holdings and global DIFund token holdings for Compound * and Aave tokens for a collateral type and staker as of * the checkpointed block, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getOtherRewardsStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker as of the checkpointed block uint96 stakerStake = stakeCollateral.diFundToken.getPriorValues(_staker, dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // Get DIFund tokens globally as of the checkpointed block uint96 globalCap = stakeCollateral.diFundToken.getTotalPriorValues(dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // If Aave, don't worry about the normalized values since 1-1 if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { return (stakerStake, globalCap, 0, 0); } // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = getUnderlyingTokenAmountForCompound(stakeCollateral.checkpointCap, stakeCollateral.exchangeRate); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice Claim other rewards (COMP and aTokens) for a claimant. * @param _claimant The address for the claimant. */ function claimOtherRewardsFromInsuranceMining(address _claimant) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain a running total of COMP to be claimed from // insurance mining contract as a by product of cToken deposits uint96 compClaimedAmountSum; // Loop through collateral names that are supported for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of Vanilla flavor, we just // continue... continue; } // Compute the DIFund token holdings and the normalized, // USDT-normalized collateral value for the user (uint96 collateralStaker, uint96 collateralTotal, uint96 normalizedCollateralStaker, ) = getOtherRewardsStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _claimant); if ((collateralTotal == 0) || (collateralStaker == 0)) { // If there are no DIFund tokens, there is no reason to // claim rewards, so we continue... continue; } if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // Aave has a special circumstance, where every // aToken results in additional aTokens accruing // to the holder's wallet. In this case, this is // the DerivaDEX contract. Therefore, we must // appropriately distribute the extra aTokens to // users claiming DDX for their aToken deposits. transferTokensAave(_claimant, dsInsuranceFund.collateralNames[i], collateralStaker, collateralTotal); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, determine the // COMP claimant is entitled to based on the COMP // yield for this interval, the claimant's // DIFundToken share, and the USD-denominated // share for this market. uint96 compClaimedAmount = dsInsuranceFund.compYields.accrued.proportion96( normalizedCollateralStaker, dsInsuranceFund.compYields.totalNormalizedCap ); // Increment the COMP claimed sum to be paid out // later compClaimedAmountSum = compClaimedAmountSum.add96(compClaimedAmount); } } // Distribute any COMP to be shared with the user if (compClaimedAmountSum > 0) { transferTokensCompound(_claimant, compClaimedAmountSum); } } /** * @notice This function transfers extra Aave aTokens to claimant. */ function transferTokensAave( address _claimant, bytes32 _collateralName, uint96 _aaveStaker, uint96 _aaveTotal ) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; uint96 aTokenClaimedAmount = dsInsuranceFund.aTokenYields[_collateralName].accrued.proportion96(_aaveStaker, _aaveTotal); // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try IAToken(stakeCollateral.collateralToken).transfer(_claimant, aTokenClaimedAmount) {} catch {} } /** * @notice This function transfers COMP tokens from the contract to * a recipient. * @param _amount Amount of COMP to receive. */ function transferTokensCompound(address _claimant, uint96 _amount) internal { // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try COMP_TOKEN.transfer(_claimant, _amount) {} catch {} } /** * @notice Updates the DDX market state to ensure that claimants can receive * their earned DDX rewards. */ function updateDDXMarketState(LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund) internal { // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 endBlock = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber); uint256 deltaBlocks = endBlock.sub(dsInsuranceFund.ddxMarketState.block); // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index uint256 index = uint256(dsInsuranceFund.ddxMarketState.index).add(ratio); // Update the claim ddx market state with the new index // and block dsInsuranceFund.ddxMarketState.index = index.safe224("IFund: exceeds 224 bits"); dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } else if (deltaBlocks > 0) { dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } } /** * @notice This function checks if a collateral token is present. * @param _collateralToken Collateral token address. * @return Whether collateral token is present or not. */ function isCollateralTokenPresent(address _collateralToken) internal view returns (bool) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Return true if collateral token has been added if ( dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]].collateralToken == _collateralToken ) { return true; } } // Collateral token has not been added, return false return false; } /** * @notice This function computes the underlying token amount for a * vanilla token. * @param _vanillaAmount Number of vanilla tokens. * @param _collateral Address of vanilla collateral. * @return Underlying token amount. */ function getUnderlyingTokenAmountForVanilla(uint96 _vanillaAmount, address _collateral) internal view returns (uint96) { uint256 vanillaDecimals = uint256(IERCCustom(_collateral).decimals()); if (vanillaDecimals >= 6) { return uint256(_vanillaAmount).div(10**(vanillaDecimals.sub(6))).safe96("IFund: amount exceeds 96 bits"); } return uint256(_vanillaAmount).mul(10**(uint256(6).sub(vanillaDecimals))).safe96("IFund: amount exceeds 96 bits"); } /** * @notice This function computes the underlying token amount for a * cToken amount by computing the current exchange rate. * @param _cTokenAmount Number of cTokens. * @param _exchangeRate Exchange rate derived from Compound. * @return Underlying token amount. */ function getUnderlyingTokenAmountForCompound(uint96 _cTokenAmount, uint256 _exchangeRate) internal pure returns (uint96) { return _exchangeRate.mul(_cTokenAmount).div(1e18).safe96("IFund: amount exceeds 96 bits."); } } // 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: MIT pragma solidity 0.6.12; /** * @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 SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add32(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(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 sub32( uint32 a, uint32 b, string memory errorMessage ) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { SafeMath96 } from "./SafeMath96.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 MathHelpers { using SafeMath96 for uint96; using SafeMath for uint256; function proportion96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(uint256(a).mul(b).div(c), "Amount exceeds 96 bits"); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } /** * @dev Returns the largest of two numbers. */ function clamp96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(Math.min(Math.max(a, b), c), "Amount exceeds 96 bits"); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; /** * @title InsuranceFundDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the insurance fund. */ library InsuranceFundDefs { // DDX market state maintaining claim index and last updated block struct DDXMarketState { uint224 index; uint32 block; } // DDX claimant state maintaining claim index and claimed DDX struct DDXClaimantState { uint256 index; uint96 claimedDDX; } // Supported collateral struct consisting of the collateral's token // addresses, collateral flavor/type, current cap and withdrawal // amounts, the latest checkpointed cap, and exchange rate (for // cTokens). An interface for the DerivaDEX Insurance Fund token // corresponding to this collateral is also maintained. struct StakeCollateral { address underlyingToken; address collateralToken; IDIFundToken diFundToken; uint96 cap; uint96 withdrawalFeeCap; uint96 checkpointCap; uint96 exchangeRate; Flavor flavor; } // Contains the yield accrued and the total normalized cap. // Total normalized cap is maintained for Compound flavors so COMP // distribution can be paid out properly struct ExternalYieldCheckpoint { uint96 accrued; uint96 totalNormalizedCap; } // Type of collateral enum Flavor { Vanilla, Compound, Aave } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { InsuranceFundDefs } from "../libs/defs/InsuranceFundDefs.sol"; import { IDIFundTokenFactory } from "../tokens/interfaces/IDIFundTokenFactory.sol"; library LibDiamondStorageInsuranceFund { struct DiamondStorageInsuranceFund { // List of supported collateral names bytes32[] collateralNames; // Collateral name to stake collateral struct mapping(bytes32 => InsuranceFundDefs.StakeCollateral) stakeCollaterals; mapping(address => InsuranceFundDefs.DDXClaimantState) ddxClaimantState; // aToken name to yield checkpoints mapping(bytes32 => InsuranceFundDefs.ExternalYieldCheckpoint) aTokenYields; mapping(address => uint256) stakerToOtherRewardsClaims; // Interval to COMP yield checkpoint InsuranceFundDefs.ExternalYieldCheckpoint compYields; // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) uint32 interval; // Current insurance mining withdrawal factor uint32 withdrawalFactor; // DDX to be issued per block as insurance mining reward uint96 mineRatePerBlock; // Incentive to advance the insurance mining interval // (e.g. 100e18 = 100 DDX) uint96 advanceIntervalReward; // Total DDX insurance mined uint96 minedAmount; // Insurance fund capitalization due to liquidations and fees uint96 liqAndFeeCapitalization; // Checkpoint block for other rewards uint256 otherRewardsCheckpointBlock; // Insurance mining final block number uint256 miningFinalBlockNumber; InsuranceFundDefs.DDXMarketState ddxMarketState; IDIFundTokenFactory diFundTokenFactory; } bytes32 constant DIAMOND_STORAGE_POSITION_INSURANCE_FUND = keccak256("diamond.standard.diamond.storage.DerivaDEX.InsuranceFund"); function diamondStorageInsuranceFund() internal pure returns (DiamondStorageInsuranceFund storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_INSURANCE_FUND; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; library LibDiamondStoragePause { struct DiamondStoragePause { bool isPaused; } bytes32 constant DIAMOND_STORAGE_POSITION_PAUSE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Pause"); function diamondStoragePause() internal pure returns (DiamondStoragePause storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_PAUSE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAToken { function decimals() external returns (uint256); function transfer(address _recipient, uint256 _amount) external; function balanceOf(address _user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; abstract contract IComptroller { struct CompMarketState { uint224 index; uint32 block; } /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; // solhint-disable-line const-name-snakecase // @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The portion of compRate that each market currently receives mapping(address => uint256) public compSpeeds; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint256) public compAccrued; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external virtual returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external virtual; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external virtual returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external virtual; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external virtual returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external virtual; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external virtual returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external virtual; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external virtual returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external virtual; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external virtual returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external virtual; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external virtual returns (uint256, uint256); function claimComp(address holder) public virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICToken { function accrueInterest() external returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOfUnderlying(address owner) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrowsCurrent() external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function decimals() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function getCash() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title IDIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ interface IDIFundToken { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function burnFrom(address _account, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorValues(address account, uint256 blockNumber) external view returns (uint96); function getTotalPriorValues(uint256 blockNumber) external view returns (uint96); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { DIFundToken } from "../DIFundToken.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ interface IDIFundTokenFactory { function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address); function diFundTokens(uint256 index) external returns (DIFundToken); function issuer() external view returns (address); function getDIFundTokens() external view returns (DIFundToken[] memory); function getDIFundTokensLength() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { IInsuranceFund } from "../facets/interfaces/IInsuranceFund.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ contract DIFundToken { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; uint256 internal _totalSupply; string private _name; string private _symbol; string private _version; uint8 private _decimals; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 values; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; mapping(uint256 => Checkpoint) totalCheckpoints; uint256 numTotalCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when a user account's balance changes event ValuesChanged(address indexed user, uint96 previousValue, uint96 newValue); /// @notice Emitted when a user account's balance changes event TotalValuesChanged(uint96 previousValue, uint96 newValue); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DIFundToken token */ constructor( string memory name, string memory symbol, uint8 decimals, address _issuer ) public { _name = name; _symbol = symbol; _decimals = decimals; _version = "1"; // Set issuer to deploying address issuer = _issuer; } /** * @notice Returns the name of the token. * @return Name of the token. */ function name() public view returns (string memory) { return _name; } /** * @notice Returns the symbol of the token. * @return Symbol of the token. */ 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}. * @return Number of decimals. */ function decimals() public view returns (uint8) { return _decimals; } /** * @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 _amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * Emits an {Approval} event indicating the updated allowance. * Requirements: * - `spender` cannot be the zero address. */ function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DIFT: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DIFT: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DIFT: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @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 _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(msg.sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _sender The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_sender][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _sender && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_sender][msg.sender] = newAllowance; emit Approval(_sender, msg.sender, newAllowance); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(_sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(_sender, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DIFT: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1) && msg.sender != issuer) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DIFT: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(_name, _version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DIFT: invalid signature."); require(_nonce == nonces[recovered]++, "DIFT: invalid nonce."); require(block.timestamp <= _expiry, "DIFT: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @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 Get the total max supply of DDX tokens * @return The total max supply of DDX */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @notice Determine the prior number of values 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 values the account had as of the given block */ function getPriorValues(address _account, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].values; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].values; } /** * @notice Determine the prior number of values 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 _blockNumber The block number to get the vote balance at * @return The number of values the account had as of the given block */ function getTotalPriorValues(uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); if (numTotalCheckpoints == 0) { return 0; } // First check most recent balance if (totalCheckpoints[numTotalCheckpoints - 1].id <= _blockNumber) { return totalCheckpoints[numTotalCheckpoints - 1].values; } // Next check implicit zero balance if (totalCheckpoints[0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numTotalCheckpoints - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = totalCheckpoints[center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return totalCheckpoints[lower].values; } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move values from spender to recipient _moveTokens(_spender, _recipient, _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); _totalSupply = _totalSupply.add(_amount); emit Transfer(address(0), _recipient, _amount); // Add value to recipient's checkpoint _moveTokens(address(0), _recipient, _amount); _writeTotalCheckpoint(_amount, true); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DIFT: not enough balance to burn."); // Reduce the circulating supply _totalSupply = _totalSupply.sub(_amount); emit Transfer(_spender, address(0), _amount); // Reduce value from spender's checkpoint _moveTokens(_spender, address(0), _amount); _writeTotalCheckpoint(_amount, false); } function _moveTokens( address _initUser, address _finUser, uint96 _amount ) internal { if (_initUser != _finUser && _amount > 0) { // Initial user address is different than final // user address and nonzero number of values moved if (_initUser != address(0)) { uint256 initUserNum = numCheckpoints[_initUser]; // Retrieve and compute the old and new initial user // address' values uint96 initUserOld = initUserNum > 0 ? checkpoints[_initUser][initUserNum - 1].values : 0; uint96 initUserNew = initUserOld.sub96(_amount); _writeCheckpoint(_initUser, initUserOld, initUserNew); } if (_finUser != address(0)) { uint256 finUserNum = numCheckpoints[_finUser]; // Retrieve and compute the old and new final user // address' values uint96 finUserOld = finUserNum > 0 ? checkpoints[_finUser][finUserNum - 1].values : 0; uint96 finUserNew = finUserOld.add96(_amount); _writeCheckpoint(_finUser, finUserOld, finUserNew); } } } function _writeCheckpoint( address _user, uint96 _oldValues, uint96 _newValues ) internal { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint256 userNum = numCheckpoints[_user]; if (userNum > 0 && checkpoints[_user][userNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_user][userNum - 1].values = _newValues; } else { // Create a new id, value pair checkpoints[_user][userNum] = Checkpoint({ id: blockNumber, values: _newValues }); numCheckpoints[_user] = userNum.add(1); } emit ValuesChanged(_user, _oldValues, _newValues); } function _writeTotalCheckpoint(uint96 _amount, bool increase) internal { if (_amount > 0) { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint96 oldValues = numTotalCheckpoints > 0 ? totalCheckpoints[numTotalCheckpoints - 1].values : 0; uint96 newValues = increase ? oldValues.add96(_amount) : oldValues.sub96(_amount); if (numTotalCheckpoints > 0 && totalCheckpoints[numTotalCheckpoints - 1].id == block.number) { // If latest checkpoint is current block, edit in place totalCheckpoints[numTotalCheckpoints - 1].values = newValues; } else { // Create a new id, value pair totalCheckpoints[numTotalCheckpoints].id = blockNumber; totalCheckpoints[numTotalCheckpoints].values = newValues; numTotalCheckpoints = numTotalCheckpoints.add(1); } emit TotalValuesChanged(oldValues, newValues); } } 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 getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } lt(source, sEnd) { } { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } slt(dest, dEnd) { } { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy(result.contentAddress(), b.contentAddress() + from, result.length); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED"); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes(bytes memory dest, bytes memory source) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"); memCopy(dest.contentAddress(), source.contentAddress(), sourceLen); } } // SPDX-License-Identifier: MIT /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return result EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return result EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibPermit { struct Permit { address spender; // Spender uint256 value; // Value uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 LibPermit Schema // bytes32 constant internal EIP712_PERMIT_SCHEMA_HASH = keccak256(abi.encodePacked( // "Permit(", // "address spender,", // "uint256 value,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_PERMIT_SCHEMA_HASH = 0x58e19c95adc541dea238d3211d11e11e7def7d0c7fda4e10e0c45eb224ef2fb7; /// @dev Calculates Keccak-256 hash of the permit. /// @param permit The permit structure. /// @return permitHash Keccak-256 EIP712 hash of the permit. function getPermitHash(Permit memory permit, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 permitHash) { permitHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashPermit(permit)); return permitHash; } /// @dev Calculates EIP712 hash of the permit. /// @param permit The permit structure. /// @return result EIP712 hash of the permit. function hashPermit(Permit memory permit) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_PERMIT_SCHEMA_HASH; assembly { // Assert permit offset (this is an internal error that should never be triggered) if lt(permit, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(permit, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 160) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IInsuranceFund { function claimDDXFromInsuranceMining(address _claimant) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { DIFundToken } from "./DIFundToken.sol"; /** * @title DIFundTokenFactory * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DIFundTokenFactory { DIFundToken[] public diFundTokens; address public issuer; /** * @notice Construct a new DDX token */ constructor(address _issuer) public { // Set issuer to deploying address issuer = _issuer; } function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address) { require(msg.sender == issuer, "DIFTF: unauthorized."); DIFundToken diFundToken = new DIFundToken(_name, _symbol, _decimals, issuer); diFundTokens.push(diFundToken); return address(diFundToken); } function getDIFundTokens() external view returns (DIFundToken[] memory) { return diFundTokens; } function getDIFundTokensLength() external view returns (uint256) { return diFundTokens.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibDelegation } from "../libs/LibDelegation.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; /** * @title DDX * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DDX { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; /// @notice ERC20 token name for this token string public constant name = "DerivaDAO"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token symbol for this token string public constant symbol = "DDX"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token decimals for this token uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase /// @notice Version number for this token. Used for EIP712 hashing. string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Max number of tokens to be issued (100 million DDX) uint96 public constant MAX_SUPPLY = 100000000e18; /// @notice Total number of tokens in circulation (50 million DDX) uint96 public constant PRE_MINE_SUPPLY = 50000000e18; /// @notice Issued supply of tokens uint96 public issuedSupply; /// @notice Current total/circulating supply of tokens uint96 public totalSupply; /// @notice Whether ownership has been transferred to the DAO bool public ownershipTransferred; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice Emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint96 previousBalance, uint96 newBalance); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DDX token */ constructor() public { // Set issuer to deploying address issuer = msg.sender; // Issue pre-mine token supply to deploying address and // set the issued and circulating supplies to pre-mine amount _transferTokensMint(msg.sender, PRE_MINE_SUPPLY); } /** * @notice Transfer ownership of DDX token from the deploying * address to the DerivaDEX Proxy/DAO * @param _derivaDEXProxy DerivaDEX Proxy address */ function transferOwnershipToDerivaDEXProxy(address _derivaDEXProxy) external { // Ensure deploying address is calling this, destination is not // the zero address, and that ownership has never been // transferred thus far require(msg.sender == issuer, "DDX: unauthorized transfer of ownership."); require(_derivaDEXProxy != address(0), "DDX: transferring to zero address."); require(!ownershipTransferred, "DDX: ownership already transferred."); // Set ownership transferred boolean flag and the new authorized // issuer ownershipTransferred = true; issuer = _derivaDEXProxy; } /** * @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 _amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * Emits an {Approval} event indicating the updated allowance. * Requirements: * - `spender` cannot be the zero address. */ function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DDX: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DDX: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DDX: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @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 _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _from The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _from, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_from][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _from && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_from][msg.sender] = newAllowance; emit Approval(_from, msg.sender, newAllowance); } // Transfer tokens from sender to recipient _transferTokens(_from, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DDX: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Ensure the mint doesn't cause the issued supply to exceed // the total supply that could ever be issued require(issuedSupply.add96(amount) <= MAX_SUPPLY, "DDX: cap exceeded."); // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1)) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DDX: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param _delegatee The address to delegate votes to */ function delegate(address _delegatee) external { _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 _signature Signature */ function delegateBySig( address _delegatee, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 delegationHash = LibDelegation.getDelegationHash( LibDelegation.Delegation({ delegatee: _delegatee, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(delegationHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Delegate votes from recovered address to delegatee _delegate(recovered, _delegatee); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @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 Gets the current votes balance. * @param _account The address to get votes balance. * @return The number of current votes. */ function getCurrentVotes(address _account) external view returns (uint96) { uint256 numCheckpointsAccount = numCheckpoints[_account]; return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 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, "DDX: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].votes; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.votes; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].votes; } function _delegate(address _delegator, address _delegatee) internal { // Get the current address delegator has delegated address currentDelegate = _getDelegatee(_delegator); // Get delegator's DDX balance uint96 delegatorBalance = balances[_delegator]; // Set delegator's new delegatee address delegates[_delegator] = _delegatee; emit DelegateChanged(_delegator, currentDelegate, _delegatee); // Move votes from currently-delegated address to // new address _moveDelegates(currentDelegate, _delegatee, delegatorBalance); } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move votes from currently-delegated address to // recipient's delegated address _moveDelegates(_getDelegatee(_spender), _getDelegatee(_recipient), _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); // Increase the issued supply and circulating supply issuedSupply = issuedSupply.add96(_amount); totalSupply = totalSupply.add96(_amount); emit Transfer(address(0), _recipient, _amount); // Add delegates to recipient's delegated address _moveDelegates(address(0), _getDelegatee(_recipient), _amount); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DDX: not enough balance to burn."); // Reduce the total supply totalSupply = totalSupply.sub96(_amount); emit Transfer(_spender, address(0), _amount); // MRedduce delegates from spender's delegated address _moveDelegates(_getDelegatee(_spender), address(0), _amount); } function _moveDelegates( address _initDel, address _finDel, uint96 _amount ) internal { if (_initDel != _finDel && _amount > 0) { // Initial delegated address is different than final // delegated address and nonzero number of votes moved if (_initDel != address(0)) { uint256 initDelNum = numCheckpoints[_initDel]; // Retrieve and compute the old and new initial delegate // address' votes uint96 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0; uint96 initDelNew = initDelOld.sub96(_amount); _writeCheckpoint(_initDel, initDelOld, initDelNew); } if (_finDel != address(0)) { uint256 finDelNum = numCheckpoints[_finDel]; // Retrieve and compute the old and new final delegate // address' votes uint96 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0; uint96 finDelNew = finDelOld.add96(_amount); _writeCheckpoint(_finDel, finDelOld, finDelNew); } } } function _writeCheckpoint( address _delegatee, uint96 _oldVotes, uint96 _newVotes ) internal { uint32 blockNumber = safe32(block.number, "DDX: exceeds 32 bits."); uint256 delNum = numCheckpoints[_delegatee]; if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_delegatee][delNum - 1].votes = _newVotes; } else { // Create a new id, vote pair checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes }); numCheckpoints[_delegatee] = delNum.add(1); } emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes); } function _getDelegatee(address _delegator) internal view returns (address) { if (delegates[_delegator] == address(0)) { return _delegator; } return delegates[_delegator]; } 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 getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibDelegation { struct Delegation { address delegatee; // Delegatee uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_DELEGATION_SCHEMA_HASH = keccak256(abi.encodePacked( // "Delegation(", // "address delegatee,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_DELEGATION_SCHEMA_HASH = 0xe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf; /// @dev Calculates Keccak-256 hash of the delegation. /// @param delegation The delegation structure. /// @return delegationHash Keccak-256 EIP712 hash of the delegation. function getDelegationHash(Delegation memory delegation, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 delegationHash) { delegationHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashDelegation(delegation)); return delegationHash; } /// @dev Calculates EIP712 hash of the delegation. /// @param delegation The delegation structure. /// @return result EIP712 hash of the delegation. function hashDelegation(Delegation memory delegation) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_DELEGATION_SCHEMA_HASH; assembly { // Assert delegation offset (this is an internal error that should never be triggered) if lt(delegation, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(delegation, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 128) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibVoteCast { struct VoteCast { uint128 proposalId; // Proposal ID bool support; // Support } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_VOTE_CAST_SCHEMA_HASH = keccak256(abi.encodePacked( // "VoteCast(", // "uint128 proposalId,", // "bool support", // ")" // )); bytes32 internal constant EIP712_VOTE_CAST_SCHEMA_HASH = 0x4abb8ae9facc09d5584ac64f616551bfc03c3ac63e5c431132305bd9bc8f8246; /// @dev Calculates Keccak-256 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return voteCastHash Keccak-256 EIP712 hash of the vote cast. function getVoteCastHash(VoteCast memory voteCast, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 voteCastHash) { voteCastHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashVoteCast(voteCast)); return voteCastHash; } /// @dev Calculates EIP712 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return result EIP712 hash of the vote cast. function hashVoteCast(VoteCast memory voteCast) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH; assembly { // Assert vote cast offset (this is an internal error that should never be triggered) if lt(voteCast, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(voteCast, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 96) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { GovernanceDefs } from "../../libs/defs/GovernanceDefs.sol"; import { LibEIP712 } from "../../libs/LibEIP712.sol"; import { LibVoteCast } from "../../libs/LibVoteCast.sol"; import { LibBytes } from "../../libs/LibBytes.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { SafeMath128 } from "../../libs/SafeMath128.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageGovernance } from "../../storage/LibDiamondStorageGovernance.sol"; /** * @title Governance * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to governance. The Diamond storage * will only be affected when facet functions are called via * the proxy contract, no checks are necessary. * @dev The Diamond storage will only be affected when facet functions * are called via the proxy contract, no checks are necessary. */ contract Governance { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath128 for uint128; using SafeMath for uint256; using MathHelpers for uint96; using MathHelpers for uint256; using LibBytes for bytes; /// @notice name for this Governance contract string public constant name = "DDX Governance"; // solhint-disable-line const-name-snakecase /// @notice version for this Governance contract string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Emitted when a new proposal is created event ProposalCreated( uint128 indexed id, address indexed proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /// @notice Emitted when a vote has been cast on a proposal event VoteCast(address indexed voter, uint128 indexed proposalId, bool support, uint96 votes); /// @notice Emitted when a proposal has been canceled event ProposalCanceled(uint128 indexed id); /// @notice Emitted when a proposal has been queued event ProposalQueued(uint128 indexed id, uint256 eta); /// @notice Emitted when a proposal has been executed event ProposalExecuted(uint128 indexed id); /// @notice Emitted when a proposal action has been canceled event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been executed event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been queued event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Governance: must be called by Governance admin."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called once and must be * done via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _quorumVotes Minimum number of for votes required, even * if there's a majority in favor. * @param _proposalThreshold Minimum DDX token holdings required * to create a proposal * @param _proposalMaxOperations Max number of operations/actions a * proposal can have * @param _votingDelay Number of blocks after a proposal is made * that voting begins. * @param _votingPeriod Number of blocks voting will be held. * @param _skipRemainingVotingThreshold Number of for or against * votes that are necessary to skip the remainder of the * voting period. * @param _gracePeriod Period in which a successful proposal must be * executed, otherwise will be expired. * @param _timelockDelay Time (s) in which a successful proposal * must be in the queue before it can be executed. */ function initialize( uint32 _proposalMaxOperations, uint32 _votingDelay, uint32 _votingPeriod, uint32 _gracePeriod, uint32 _timelockDelay, uint32 _quorumVotes, uint32 _proposalThreshold, uint32 _skipRemainingVotingThreshold ) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure state variable comparisons are valid requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, _quorumVotes); // Set initial variable values dsGovernance.proposalMaxOperations = _proposalMaxOperations; dsGovernance.votingDelay = _votingDelay; dsGovernance.votingPeriod = _votingPeriod; dsGovernance.gracePeriod = _gracePeriod; dsGovernance.timelockDelay = _timelockDelay; dsGovernance.quorumVotes = _quorumVotes; dsGovernance.proposalThreshold = _proposalThreshold; dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; dsGovernance.fastPathFunctionSignatures["setIsPaused(bool)"] = true; } /** * @notice This function allows participants who have sufficient * DDX holdings to create new proposals up for vote. The * proposals contain the ordered lists of on-chain * executable calldata. * @param _targets Addresses of contracts involved. * @param _values Values to be passed along with the calls. * @param _signatures Function signatures. * @param _calldatas Calldata passed to the function. * @param _description Text description of proposal. */ function propose( address[] memory _targets, uint256[] memory _values, string[] memory _signatures, bytes[] memory _calldatas, string memory _description ) external returns (uint128) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposer has sufficient token holdings to propose require( dsDerivaDEX.ddxToken.getPriorVotes(msg.sender, block.number.sub(1)) >= getProposerThresholdCount(), "Governance: proposer votes below proposal threshold." ); require( _targets.length == _values.length && _targets.length == _signatures.length && _targets.length == _calldatas.length, "Governance: proposal function information parity mismatch." ); require(_targets.length != 0, "Governance: must provide actions."); require(_targets.length <= dsGovernance.proposalMaxOperations, "Governance: too many actions."); if (dsGovernance.latestProposalIds[msg.sender] != 0) { // Ensure proposer doesn't already have one active/pending GovernanceDefs.ProposalState proposersLatestProposalState = state(dsGovernance.latestProposalIds[msg.sender]); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Active, "Governance: one live proposal per proposer, found an already active proposal." ); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Pending, "Governance: one live proposal per proposer, found an already pending proposal." ); } // Proposal voting starts votingDelay after proposal is made uint256 startBlock = block.number.add(dsGovernance.votingDelay); // Increment count of proposals dsGovernance.proposalCount++; // Create new proposal struct and add to mapping GovernanceDefs.Proposal memory newProposal = GovernanceDefs.Proposal({ id: dsGovernance.proposalCount, proposer: msg.sender, delay: getTimelockDelayForSignatures(_signatures), eta: 0, targets: _targets, values: _values, signatures: _signatures, calldatas: _calldatas, startBlock: startBlock, endBlock: startBlock.add(dsGovernance.votingPeriod), forVotes: 0, againstVotes: 0, canceled: false, executed: false }); dsGovernance.proposals[newProposal.id] = newProposal; // Update proposer's latest proposal dsGovernance.latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, _targets, _values, _signatures, _calldatas, startBlock, startBlock.add(dsGovernance.votingPeriod), _description ); return newProposal.id; } /** * @notice This function allows any participant to queue a * successful proposal for execution. Proposals are deemed * successful if at any point the number of for votes has * exceeded the skip remaining voting threshold or if there * is a simple majority (and more for votes than the * minimum quorum) at the end of voting. * @param _proposalId Proposal id. */ function queue(uint128 _proposalId) external { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal has succeeded (i.e. it has either enough for // votes to skip the remainder of the voting period or the // voting period has ended and there is a simple majority in // favor and also above the quorum require( state(_proposalId) == GovernanceDefs.ProposalState.Succeeded, "Governance: proposal can only be queued if it is succeeded." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Establish eta of execution, which is a number of seconds // after queuing at which point proposal can actually execute uint256 eta = block.timestamp.add(proposal.delay); for (uint256 i = 0; i < proposal.targets.length; i++) { // Ensure proposal action is not already in the queue bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ) ); require(!dsGovernance.queuedTransactions[txHash], "Governance: proposal action already queued at eta."); dsGovernance.queuedTransactions[txHash] = true; emit QueueTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } // Set proposal eta timestamp after which it can be executed proposal.eta = eta; emit ProposalQueued(_proposalId, eta); } /** * @notice This function allows any participant to execute a * queued proposal. A proposal in the queue must be in the * queue for the delay period it was proposed with prior to * executing, allowing the community to position itself * accordingly. * @param _proposalId Proposal id. */ function execute(uint128 _proposalId) external payable { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal is queued require( state(_proposalId) == GovernanceDefs.ProposalState.Queued, "Governance: proposal can only be executed if it is queued." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposal has been in the queue long enough require(block.timestamp >= proposal.eta, "Governance: proposal hasn't finished queue time length."); // Ensure proposal hasn't been in the queue for too long require(block.timestamp <= proposal.eta.add(dsGovernance.gracePeriod), "Governance: transaction is stale."); proposal.executed = true; // Loop through each of the actions in the proposal for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); require(dsGovernance.queuedTransactions[txHash], "Governance: transaction hasn't been queued."); dsGovernance.queuedTransactions[txHash] = false; // Execute action bytes memory callData; require(bytes(proposal.signatures[i]).length != 0, "Governance: Invalid function signature."); callData = abi.encodePacked(bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i]); // solium-disable-next-line security/no-call-value (bool success, ) = proposal.targets[i].call{ value: proposal.values[i] }(callData); require(success, "Governance: transaction execution reverted."); emit ExecuteTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalExecuted(_proposalId); } /** * @notice This function allows any participant to cancel any non- * executed proposal. It can be canceled if the proposer's * token holdings has dipped below the proposal threshold * at the time of cancellation. * @param _proposalId Proposal id. */ function cancel(uint128 _proposalId) external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.ProposalState state = state(_proposalId); // Ensure proposal hasn't executed require(state != GovernanceDefs.ProposalState.Executed, "Governance: cannot cancel executed proposal."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposer's token holdings has dipped below the // proposer threshold, leaving their proposal subject to // cancellation require( dsDerivaDEX.ddxToken.getPriorVotes(proposal.proposer, block.number.sub(1)) < getProposerThresholdCount(), "Governance: proposer above threshold." ); proposal.canceled = true; // Loop through each of the proposal's actions for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); dsGovernance.queuedTransactions[txHash] = false; emit CancelTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalCanceled(_proposalId); } /** * @notice This function allows participants to cast either in * favor or against a particular proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). */ function castVote(uint128 _proposalId, bool _support) external { return _castVote(msg.sender, _proposalId, _support); } /** * @notice This function allows participants to cast votes with * offline signatures in favor or against a particular * proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). * @param _signature Signature */ function castVoteBySig( uint128 _proposalId, bool _support, bytes memory _signature ) external { // EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 voteCastHash = LibVoteCast.getVoteCastHash( LibVoteCast.VoteCast({ proposalId: _proposalId, support: _support }), eip712OrderParamsDomainHash ); // Recover the signature and EIP712 hash uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(voteCastHash, v, r, s); require(recovered != address(0), "Governance: invalid signature."); return _castVote(recovered, _proposalId, _support); } /** * @notice This function sets the quorum votes required for a * proposal to pass. It must be called via * governance. * @param _quorumVotes Quorum votes threshold. */ function setQuorumVotes(uint32 _quorumVotes) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireSkipRemainingVotingThresholdGtQuorumVotes(dsGovernance.skipRemainingVotingThreshold, _quorumVotes); dsGovernance.quorumVotes = _quorumVotes; } /** * @notice This function sets the token holdings threshold required * to propose something. It must be called via * governance. * @param _proposalThreshold Proposal threshold. */ function setProposalThreshold(uint32 _proposalThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalThreshold = _proposalThreshold; } /** * @notice This function sets the max operations a proposal can * carry out. It must be called via governance. * @param _proposalMaxOperations Proposal's max operations. */ function setProposalMaxOperations(uint32 _proposalMaxOperations) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalMaxOperations = _proposalMaxOperations; } /** * @notice This function sets the voting delay in blocks from when * a proposal is made and voting begins. It must be called * via governance. * @param _votingDelay Voting delay (blocks). */ function setVotingDelay(uint32 _votingDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingDelay = _votingDelay; } /** * @notice This function sets the voting period in blocks that a * vote will last. It must be called via * governance. * @param _votingPeriod Voting period (blocks). */ function setVotingPeriod(uint32 _votingPeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingPeriod = _votingPeriod; } /** * @notice This function sets the threshold at which a proposal can * immediately be deemed successful or rejected if the for * or against votes exceeds this threshold, even if the * voting period is still ongoing. It must be called * governance. * @param _skipRemainingVotingThreshold Threshold for or against * votes must reach to skip remainder of voting period. */ function setSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, dsGovernance.quorumVotes); dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; } /** * @notice This function sets the grace period in seconds that a * queued proposal can last before expiring. It must be * called via governance. * @param _gracePeriod Grace period (seconds). */ function setGracePeriod(uint32 _gracePeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.gracePeriod = _gracePeriod; } /** * @notice This function sets the timelock delay (s) a proposal * must be queued before execution. * @param _timelockDelay Timelock delay (seconds). */ function setTimelockDelay(uint32 _timelockDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.timelockDelay = _timelockDelay; } /** * @notice This function allows any participant to retrieve * the actions involved in a given proposal. * @param _proposalId Proposal id. * @return targets Addresses of contracts involved. * @return values Values to be passed along with the calls. * @return signatures Function signatures. * @return calldatas Calldata passed to the function. */ function getActions(uint128 _proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal storage p = dsGovernance.proposals[_proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice This function allows any participant to retrieve * the receipt for a given proposal and voter. * @param _proposalId Proposal id. * @param _voter Voter address. * @return Voter receipt. */ function getReceipt(uint128 _proposalId, address _voter) external view returns (GovernanceDefs.Receipt memory) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposals[_proposalId].receipts[_voter]; } /** * @notice This function gets a proposal from an ID. * @param _proposalId Proposal id. * @return Proposal attributes. */ function getProposal(uint128 _proposalId) external view returns ( bool, bool, address, uint32, uint96, uint96, uint128, uint256, uint256, uint256 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal memory proposal = dsGovernance.proposals[_proposalId]; return ( proposal.canceled, proposal.executed, proposal.proposer, proposal.delay, proposal.forVotes, proposal.againstVotes, proposal.id, proposal.eta, proposal.startBlock, proposal.endBlock ); } /** * @notice This function gets whether a proposal action transaction * hash is queued or not. * @param _txHash Proposal action tx hash. * @return Is proposal action transaction hash queued or not. */ function getIsQueuedTransaction(bytes32 _txHash) external view returns (bool) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.queuedTransactions[_txHash]; } /** * @notice This function gets the Governance facet's current * parameters. * @return Proposal max operations. * @return Voting delay. * @return Voting period. * @return Grace period. * @return Timelock delay. * @return Quorum votes threshold. * @return Proposal threshold. * @return Skip remaining voting threshold. */ function getGovernanceParameters() external view returns ( uint32, uint32, uint32, uint32, uint32, uint32, uint32, uint32 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return ( dsGovernance.proposalMaxOperations, dsGovernance.votingDelay, dsGovernance.votingPeriod, dsGovernance.gracePeriod, dsGovernance.timelockDelay, dsGovernance.quorumVotes, dsGovernance.proposalThreshold, dsGovernance.skipRemainingVotingThreshold ); } /** * @notice This function gets the proposal count. * @return Proposal count. */ function getProposalCount() external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposalCount; } /** * @notice This function gets the latest proposal ID for a user. * @param _proposer Proposer's address. * @return Proposal ID. */ function getLatestProposalId(address _proposer) external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.latestProposalIds[_proposer]; } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getQuorumVoteCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.quorumVotes, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getProposerThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.proposalThreshold, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getSkipRemainingVotingThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.skipRemainingVotingThreshold, 100); } /** * @notice This function retrieves the status for any given * proposal. * @param _proposalId Proposal id. * @return Status of proposal. */ function state(uint128 _proposalId) public view returns (GovernanceDefs.ProposalState) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(dsGovernance.proposalCount >= _proposalId && _proposalId > 0, "Governance: invalid proposal id."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Note the 3rd conditional where we can escape out of the vote // phase if the for or against votes exceeds the skip remaining // voting threshold if (proposal.canceled) { return GovernanceDefs.ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return GovernanceDefs.ProposalState.Pending; } else if ( (block.number <= proposal.endBlock) && (proposal.forVotes < getSkipRemainingVotingThresholdCount()) && (proposal.againstVotes < getSkipRemainingVotingThresholdCount()) ) { return GovernanceDefs.ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < getQuorumVoteCount()) { return GovernanceDefs.ProposalState.Defeated; } else if (proposal.eta == 0) { return GovernanceDefs.ProposalState.Succeeded; } else if (proposal.executed) { return GovernanceDefs.ProposalState.Executed; } else if (block.timestamp >= proposal.eta.add(dsGovernance.gracePeriod)) { return GovernanceDefs.ProposalState.Expired; } else { return GovernanceDefs.ProposalState.Queued; } } function _castVote( address _voter, uint128 _proposalId, bool _support ) internal { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(state(_proposalId) == GovernanceDefs.ProposalState.Active, "Governance: voting is closed."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; GovernanceDefs.Receipt storage receipt = proposal.receipts[_voter]; // Ensure voter has not already voted require(!receipt.hasVoted, "Governance: voter already voted."); // Obtain the token holdings (voting power) for participant at // the time voting started. They may have gained or lost tokens // since then, doesn't matter. uint96 votes = dsDerivaDEX.ddxToken.getPriorVotes(_voter, proposal.startBlock); // Ensure voter has nonzero voting power require(votes > 0, "Governance: voter has no voting power."); if (_support) { // Increment the for votes in favor proposal.forVotes = proposal.forVotes.add96(votes); } else { // Increment the against votes proposal.againstVotes = proposal.againstVotes.add96(votes); } // Set receipt attributes based on cast vote parameters receipt.hasVoted = true; receipt.support = _support; receipt.votes = votes; emit VoteCast(_voter, _proposalId, _support, votes); } function getTimelockDelayForSignatures(string[] memory _signatures) internal view returns (uint32) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); for (uint256 i = 0; i < _signatures.length; i++) { if (!dsGovernance.fastPathFunctionSignatures[_signatures[i]]) { return dsGovernance.timelockDelay; } } return 1; } function requireSkipRemainingVotingThresholdGtQuorumVotes(uint32 _skipRemainingVotingThreshold, uint32 _quorumVotes) internal pure { require(_skipRemainingVotingThreshold > _quorumVotes, "Governance: skip rem votes must be higher than quorum."); } function requireValidSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) internal pure { require(_skipRemainingVotingThreshold >= 50, "Governance: skip rem votes must be higher than 50pct."); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title GovernanceDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the governance. */ library GovernanceDefs { struct Proposal { bool canceled; bool executed; address proposer; uint32 delay; uint96 forVotes; uint96 againstVotes; uint128 id; uint256 eta; address[] targets; string[] signatures; bytes[] calldatas; uint256[] values; uint256 startBlock; uint256 endBlock; mapping(address => Receipt) receipts; } struct Receipt { bool hasVoted; bool support; uint96 votes; } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint128 a, uint128 b) internal pure returns (uint128) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint128 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { GovernanceDefs } from "../libs/defs/GovernanceDefs.sol"; library LibDiamondStorageGovernance { struct DiamondStorageGovernance { // Proposal struct by ID mapping(uint256 => GovernanceDefs.Proposal) proposals; // Latest proposal IDs by proposer address mapping(address => uint128) latestProposalIds; // Whether transaction hash is currently queued mapping(bytes32 => bool) queuedTransactions; // Fast path for governance mapping(string => bool) fastPathFunctionSignatures; // Max number of operations/actions a proposal can have uint32 proposalMaxOperations; // Number of blocks after a proposal is made that voting begins // (e.g. 1 block) uint32 votingDelay; // Number of blocks voting will be held // (e.g. 17280 blocks ~ 3 days of blocks) uint32 votingPeriod; // Time window (s) a successful proposal must be executed, // otherwise will be expired, measured in seconds // (e.g. 1209600 seconds) uint32 gracePeriod; // Minimum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 0 seconds) uint32 minimumDelay; // Maximum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 2592000 seconds ~ 30 days) uint32 maximumDelay; // Minimum number of for votes required, even if there's a // majority in favor // (e.g. 2000000e18 ~ 4% of pre-mine DDX supply) uint32 quorumVotes; // Minimum DDX token holdings required to create a proposal // (e.g. 500000e18 ~ 1% of pre-mine DDX supply) uint32 proposalThreshold; // Number of for or against votes that are necessary to skip // the remainder of the voting period // (e.g. 25000000e18 tokens/votes) uint32 skipRemainingVotingThreshold; // Time (s) proposals must be queued before executing uint32 timelockDelay; // Total number of proposals uint128 proposalCount; } bytes32 constant DIAMOND_STORAGE_POSITION_GOVERNANCE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Governance"); function diamondStorageGovernance() internal pure returns (DiamondStorageGovernance storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_GOVERNANCE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; /** * @title Pause * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to pausing functionality. The purpose * of this is to ensure the system can pause in the unlikely * scenario of a bug or issue materially jeopardizing users' * funds or experience. This facet will be removed entirely * as the system stabilizes shortly. It's important to note that * unlike the vast majority of projects, even during this * short-lived period of time in which the system can be paused, * no single admin address can wield this power, but rather * pausing must be carried out via governance. */ contract Pause { event PauseInitialized(); event IsPausedSet(bool isPaused); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Pause: must be called by Gov."); _; } /** * @notice This function initializes the facet. */ function initialize() external onlyAdmin { emit PauseInitialized(); } /** * @notice This function sets the paused status. * @param _isPaused Whether contracts are paused or not. */ function setIsPaused(bool _isPaused) external onlyAdmin { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); dsPause.isPaused = _isPaused; emit IsPausedSet(_isPaused); } /** * @notice This function gets whether the contract ecosystem is * currently paused. * @return Whether contracts are paused or not. */ function getIsPaused() public view returns (bool) { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); return dsPause.isPaused; } } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2019-07-18 */ pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Ownable } from "openzeppelin-solidity/contracts/access/Ownable.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; library Roles { struct Role { mapping(address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Ownable { using Roles for Roles.Role; Roles.Role private _pausers; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyOwner { _addPauser(account); } function removePauser(address account) public onlyOwner { _removePauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { bool private _paused; event Paused(address account); event Unpaused(address account); constructor() internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20 is IERC20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; event Issue(address indexed account, uint256 amount); event Redeem(address indexed account, uint256 value); function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public virtual override returns (bool) { _approve(msg.sender, spender, value); 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)); 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)); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 value ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _issue(address account, uint256 amount) internal { require(account != address(0), "CoinFactory: issue to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); emit Issue(account, amount); } function _redeem(address account, uint256 value) internal { require(account != address(0), "CoinFactory: redeem from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); emit Redeem(account, value); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public virtual override whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public virtual override whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } contract CoinFactoryAdminRole is Ownable { using Roles for Roles.Role; event CoinFactoryAdminRoleAdded(address indexed account); event CoinFactoryAdminRoleRemoved(address indexed account); Roles.Role private _coinFactoryAdmins; constructor() internal { _addCoinFactoryAdmin(msg.sender); } modifier onlyCoinFactoryAdmin() { require(isCoinFactoryAdmin(msg.sender), "CoinFactoryAdminRole: caller does not have the CoinFactoryAdmin role"); _; } function isCoinFactoryAdmin(address account) public view returns (bool) { return _coinFactoryAdmins.has(account); } function addCoinFactoryAdmin(address account) public onlyOwner { _addCoinFactoryAdmin(account); } function removeCoinFactoryAdmin(address account) public onlyOwner { _removeCoinFactoryAdmin(account); } function renounceCoinFactoryAdmin() public { _removeCoinFactoryAdmin(msg.sender); } function _addCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.add(account); emit CoinFactoryAdminRoleAdded(account); } function _removeCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.remove(account); emit CoinFactoryAdminRoleRemoved(account); } } contract CoinFactory is ERC20, CoinFactoryAdminRole { function issue(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _issue(account, amount); return true; } function redeem(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _redeem(account, amount); return true; } } contract BlacklistAdminRole is Ownable { using Roles for Roles.Role; event BlacklistAdminAdded(address indexed account); event BlacklistAdminRemoved(address indexed account); Roles.Role private _blacklistAdmins; constructor() internal { _addBlacklistAdmin(msg.sender); } modifier onlyBlacklistAdmin() { require(isBlacklistAdmin(msg.sender), "BlacklistAdminRole: caller does not have the BlacklistAdmin role"); _; } function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); } function addBlacklistAdmin(address account) public onlyOwner { _addBlacklistAdmin(account); } function removeBlacklistAdmin(address account) public onlyOwner { _removeBlacklistAdmin(account); } function renounceBlacklistAdmin() public { _removeBlacklistAdmin(msg.sender); } function _addBlacklistAdmin(address account) internal { _blacklistAdmins.add(account); emit BlacklistAdminAdded(account); } function _removeBlacklistAdmin(address account) internal { _blacklistAdmins.remove(account); emit BlacklistAdminRemoved(account); } } contract Blacklist is ERC20, BlacklistAdminRole { mapping(address => bool) private _blacklist; event BlacklistAdded(address indexed account); event BlacklistRemoved(address indexed account); function addBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _addBlacklist(accounts[i]); } } function removeBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _removeBlacklist(accounts[i]); } } function isBlacklist(address account) public view returns (bool) { return _blacklist[account]; } function _addBlacklist(address account) internal { _blacklist[account] = true; emit BlacklistAdded(account); } function _removeBlacklist(address account) internal { _blacklist[account] = false; emit BlacklistRemoved(account); } } contract HDUMToken is ERC20, ERC20Pausable, CoinFactory, Blacklist { string public name; string public symbol; uint8 public decimals; uint256 private _totalSupply; constructor( string memory _name, string memory _symbol, uint8 _decimals ) public { _totalSupply = 0; name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address to, uint256 value) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transferFrom"); require(!isBlacklist(from), "HDUMToken: from in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // 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: 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.12; pragma experimental ABIEncoderV2; import { Context } from "openzeppelin-solidity/contracts/GSN/Context.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract SafeERC20Wrapper is Context { using SafeERC20 for IERC20; IERC20 private _token; constructor(IERC20 token) public { _token = token; } function transfer(address recipient, uint256 amount) public { _token.safeTransfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public { _token.safeTransferFrom(sender, recipient, amount); } function approve(address spender, uint256 amount) public { _token.safeApprove(spender, amount); } function increaseAllowance(address spender, uint256 amount) public { _token.safeIncreaseAllowance(spender, amount); } function decreaseAllowance(address spender, uint256 amount) public { _token.safeDecreaseAllowance(spender, amount); } function allowance(address owner, address spender) public view returns (uint256) { return _token.allowance(owner, spender); } function balanceOf(address account) public view returns (uint256) { return _token.balanceOf(account); } } // 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.12; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; // mock class using ERC20 contract DummyToken is ERC20 { uint256 public constant INITIAL_SUPPLY = 100000000 * (10**18); constructor(string memory name, string memory symbol) public payable ERC20(name, symbol) { _mint(msg.sender, INITIAL_SUPPLY); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } function transferInternal( address from, address to, uint256 value ) public { _transfer(from, to, value); } function approveInternal( address owner, address spender, uint256 value ) public { _approve(owner, spender, value); } }
Get the number of tokens held by the `account` _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]; }
1,813,682
./full_match/4/0x8Ff4b4c84940092eee58BC3583dF417489B64F27/sources/browser/ERC1363PayableCrowdsale.sol
return the amount of ERC1363 token raised./
function tokenRaised() public view returns (uint256) { return _tokenRaised; }
12,367,986
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol pragma solidity ^0.5.4; interface IntVoteInterface { //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier ONLYPROPOSALOWNER208(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING modifier VOTABLE853(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING event NEWPROPOSAL588( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event EXECUTEPROPOSAL706(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VOTEPROPOSAL760( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CANCELPROPOSAL161(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING event CANCELVOTING574(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING function PROPOSE661( //inject NONSTANDARD NAMING uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function VOTE536( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function CANCELVOTE202(bytes32 _proposalId) external; //inject NONSTANDARD NAMING function GETNUMBEROFCHOICES589(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function ISVOTABLE375(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING function ISABSTAINALLOW791() external pure returns(bool); //inject NONSTANDARD NAMING function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; interface IERC20 { function TRANSFER985(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE946(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM649(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY573() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF995(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE88(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER258(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL578(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol pragma solidity ^0.5.4; interface VotingMachineCallbacksInterface { function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function BURNREPUTATION898(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function STAKINGTOKENTRANSFER53(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING external returns(bool); function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED48(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED48(address(0), _owner); } function OWNER574() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER824() { //inject NONSTANDARD NAMING require(ISOWNER625()); _; } function ISOWNER625() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP632() public ONLYOWNER824 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED48(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP334(address newOwner) public ONLYOWNER824 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP900(newOwner); } function _TRANSFEROWNERSHIP900(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED48(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol pragma solidity ^0.5.4; contract Reputation is Ownable { uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event MINT335(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING // Event indicating burning of reputation for an address. event BURN261(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of reputation at a specific block number uint128 value; } // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // Tracks the history of the `totalSupply` of the reputation Checkpoint[] totalSupplyHistory; constructor( ) public { } function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING return TOTALSUPPLYAT652(block.number); } // Query balance and totalSupply in History function BALANCEOF995(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return BALANCEOFAT780(_owner, block.number); } function BALANCEOFAT780(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING public view returns (uint256) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return GETVALUEAT483(balances[_owner], _blockNumber); } } function TOTALSUPPLYAT652(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return GETVALUEAT483(totalSupplyHistory, _blockNumber); } } function MINT69(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY573(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = BALANCEOF995(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply + _amount); UPDATEVALUEATNOW719(balances[_user], previousBalanceTo + _amount); emit MINT335(_user, _amount); return true; } function BURN206(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY573(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = BALANCEOF995(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply - amountBurned); UPDATEVALUEATNOW719(balances[_user], previousBalanceFrom - amountBurned); emit BURN261(_user, amountBurned); return true; } // Internal helper functions to query and set a value in a snapshot array function GETVALUEAT483(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function UPDATEVALUEATNOW719(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING require(uint128(_value) == _value); //check value is in the 128 bits bounderies if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; library SafeMath { function MUL295(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); return c; } function DIV1(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB141(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD15(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD36(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF995(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE88(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER985(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER402(msg.sender, to, value); return true; } function APPROVE946(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, value); return true; } function TRANSFERFROM649(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER402(from, to, value); _APPROVE913(from, msg.sender, _allowed[from][msg.sender].SUB141(value)); return true; } function INCREASEALLOWANCE616(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].ADD15(addedValue)); return true; } function DECREASEALLOWANCE72(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].SUB141(subtractedValue)); return true; } function _TRANSFER402(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB141(value); _balances[to] = _balances[to].ADD15(value); emit TRANSFER258(from, to, value); } function _MINT318(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD15(value); _balances[account] = _balances[account].ADD15(value); emit TRANSFER258(address(0), account, value); } function _BURN875(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB141(value); _balances[account] = _balances[account].SUB141(value); emit TRANSFER258(account, address(0), value); } function _APPROVE913(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL578(owner, spender, value); } function _BURNFROM507(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN875(account, value); _APPROVE913(account, msg.sender, _allowed[account][msg.sender].SUB141(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; contract ERC20Burnable is ERC20 { function BURN206(uint256 value) public { //inject NONSTANDARD NAMING _BURN875(msg.sender, value); } function BURNFROM991(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM507(from, value); } } // File: contracts/controller/DAOToken.sol pragma solidity ^0.5.4; contract DAOToken is ERC20, ERC20Burnable, Ownable { string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals662 = 18; //inject NONSTANDARD NAMING uint256 public cap; constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } function MINT69(address _to, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING if (cap > 0) require(TOTALSUPPLY573().ADD15(_amount) <= cap); _MINT318(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.2; library Address { function ISCONTRACT51(address account) internal view returns (bool) { //inject NONSTANDARD NAMING 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/libs/SafeERC20.sol pragma solidity ^0.5.4; library SafeERC20 { using Address for address; bytes4 constant private transfer_selector475 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private transferfrom_selector4 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private approve_selector816 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING function SAFETRANSFER442(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transfer_selector475, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFETRANSFERFROM294(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transferfrom_selector4, _from, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFEAPPROVE771(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (IERC20(_erc20Addr).ALLOWANCE88(address(this), _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(approve_selector816, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: contracts/controller/Avatar.sol pragma solidity ^0.5.4; contract Avatar is Ownable { using SafeERC20 for address; string public orgName; DAOToken public nativeToken; Reputation public nativeReputation; event GENERICCALL988(address indexed _contract, bytes _data, uint _value, bool _success); //inject NONSTANDARD NAMING event SENDETHER194(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFER653(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFERFROM913(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENAPPROVAL142(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING event RECEIVEETHER18(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING event METADATA150(string _metaData); //inject NONSTANDARD NAMING constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } function() external payable { emit RECEIVEETHER18(msg.sender, msg.value); } function GENERICCALL327(address _contract, bytes memory _data, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-call-value (success, returnValue) = _contract.call.value(_value)(_data); emit GENERICCALL988(_contract, _data, _value, success); } function SENDETHER177(uint256 _amountInWei, address payable _to) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING _to.transfer(_amountInWei); emit SENDETHER194(_amountInWei, _to); return true; } function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool) { address(_externalToken).SAFETRANSFER442(_to, _value); emit EXTERNALTOKENTRANSFER653(address(_externalToken), _to, _value); return true; } function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING IERC20 _externalToken, address _from, address _to, uint256 _value ) public ONLYOWNER824 returns(bool) { address(_externalToken).SAFETRANSFERFROM294(_from, _to, _value); emit EXTERNALTOKENTRANSFERFROM913(address(_externalToken), _from, _to, _value); return true; } function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool) { address(_externalToken).SAFEAPPROVE771(_spender, _value); emit EXTERNALTOKENAPPROVAL142(address(_externalToken), _spender, _value); return true; } function METADATA450(string memory _metaData) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING emit METADATA150(_metaData); return true; } } // File: contracts/universalSchemes/UniversalSchemeInterface.sol pragma solidity ^0.5.4; contract UniversalSchemeInterface { function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING } // File: contracts/globalConstraints/GlobalConstraintInterface.sol pragma solidity ^0.5.4; contract GlobalConstraintInterface { enum CallPhase { Pre, Post, PreAndPost } function PRE222( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function POST74( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function WHEN422() public returns(CallPhase); //inject NONSTANDARD NAMING } // File: contracts/controller/ControllerInterface.sol pragma solidity ^0.5.4; interface ControllerInterface { function MINTREPUTATION981(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function BURNREPUTATION898(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function MINTTOKENS758(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REGISTERSCHEME37(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSCHEME785(address _scheme, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSELF96(address _avatar) external returns(bool); //inject NONSTANDARD NAMING function ADDGLOBALCONSTRAINT638(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REMOVEGLOBALCONSTRAINT28 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UPGRADECONTROLLER721(address _newController, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function GENERICCALL327(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value) //inject NONSTANDARD NAMING external returns(bool, bytes memory); function SENDETHER177(uint256 _amountInWei, address payable _to, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING IERC20 _externalToken, address _from, address _to, uint256 _value, Avatar _avatar) external returns(bool); function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function METADATA450(string calldata _metaData, Avatar _avatar) external returns(bool); //inject NONSTANDARD NAMING function GETNATIVEREPUTATION762(address _avatar) //inject NONSTANDARD NAMING external view returns(address); function ISSCHEMEREGISTERED658( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING function GETSCHEMEPARAMETERS578(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETGLOBALCONSTRAINTPARAMETERS702(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETSCHEMEPERMISSIONS800(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING function GLOBALCONSTRAINTSCOUNT83(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING function ISGLOBALCONSTRAINTREGISTERED605(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING } // File: contracts/universalSchemes/UniversalScheme.sol pragma solidity ^0.5.4; contract UniversalScheme is UniversalSchemeInterface { function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING require(ControllerInterface(_avatar.OWNER574()).ISSCHEMEREGISTERED658(address(this), address(_avatar)), "scheme is not registered"); return ControllerInterface(_avatar.OWNER574()).GETSCHEMEPARAMETERS578(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.2; library ECDSA { function RECOVER336(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } function TOETHSIGNEDMESSAGEHASH747(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: @daostack/infra/contracts/libs/RealMath.sol pragma solidity ^0.5.4; library RealMath { uint256 constant private real_bits978 = 256; //inject NONSTANDARD NAMING uint256 constant private real_fbits102 = 40; //inject NONSTANDARD NAMING uint256 constant private real_one722 = uint256(1) << real_fbits102; //inject NONSTANDARD NAMING function POW948(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = real_one722; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = MUL295(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; if (tempExponent != 0) { // Do the squaring tempRealBase = MUL295(tempRealBase, tempRealBase); } } // Return the final result. return realResult; } function FRACTION401(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV1(uint256(numerator) * real_one722, uint256(denominator) * real_one722); } function MUL295(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. uint256 res = realA * realB; require(res/realA == realB, "RealMath mul overflow"); return (res >> real_fbits102); } function DIV1(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return uint256((uint256(realNumerator) * real_one722) / uint256(realDenominator)); } } // File: @daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol pragma solidity ^0.5.4; interface ProposalExecuteInterface { function EXECUTEPROPOSAL422(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; library Math { function MAX135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN317(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE86(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol pragma solidity ^0.5.4; contract GenesisProtocolLogic is IntVoteInterface { using SafeMath for uint256; using Math for uint256; using RealMath for uint216; using RealMath for uint256; using Address for address; enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod} enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed} //Organization's parameters struct Parameters { uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar. uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode. uint256 preBoostedVotePeriodLimit; //the time limit for a proposal //to be in an preparation state (stable) before boosted. uint256 thresholdConst; //constant for threshold calculation . //threshold =thresholdConst ** (numberOfBoostedProposals) uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals //in the threshold calculation to prevent overflow uint256 quietEndingPeriod; //quite ending period uint256 proposingRepReward;//proposer reputation reward. uint256 votersReputationLossRatio;//Unsuccessful pre booster //voters lose votersReputationLossRatio% of their reputation. uint256 minimumDaoBounty; uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula //(daoBountyConst * averageBoostDownstakes)/100 . uint256 activationTime;//the point in time after which proposals can be created. //if this address is set so only this address is allowed to vote of behalf of someone else. address voteOnBehalf; } struct Voter { uint256 vote; // YES(1) ,NO(2) uint256 reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint256 vote; // YES(1) ,NO(2) uint256 amount; // amount of staker's stake uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation. } struct Proposal { bytes32 organizationId; // the organization unique identifier the proposal is target to. address callbacks; // should fulfill voting callbacks interface. ProposalState state; uint256 winningVote; //the winning vote. address proposer; //the proposal boosted period limit . it is updated for the case of quiteWindow mode. uint256 currentBoostedVotePeriodLimit; bytes32 paramsHash; uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time. uint256 daoBounty; uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers. uint256 confidenceThreshold; //The percentage from upper stakes which the caller for the expiration was given. uint256 expirationCallBountyPercentage; uint[3] times; //times[0] - submittedTime //times[1] - boostedPhaseTime //times[2] -preBoostedPhaseTime; bool daoRedeemItsWinnings; // vote reputation mapping(uint256 => uint256 ) votes; // vote reputation mapping(uint256 => uint256 ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint256 => uint256 ) stakes; // address staker mapping(address => Staker ) stakers; } event STAKE754(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event REDEEM636(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMDAOBOUNTY578(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMREPUTATION314(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event STATECHANGE374(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING event GPEXECUTEPROPOSAL538(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING event EXPIRATIONCALLBOUNTY93(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING event CONFIDENCELEVELCHANGE532(bytes32 indexed _proposalId, uint256 _confidenceThreshold); //inject NONSTANDARD NAMING mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes32=>uint) public orgBoostedProposalsCnt; //organizationId => organization mapping(bytes32 => address ) public organizations; //organizationId => averageBoostDownstakes mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted; uint256 constant public num_of_choices613 = 2; //inject NONSTANDARD NAMING uint256 constant public no391 = 2; //inject NONSTANDARD NAMING uint256 constant public yes596 = 1; //inject NONSTANDARD NAMING uint256 public proposalsCnt; // Total number of proposals IERC20 public stakingToken; address constant private gen_token_address929 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING uint256 constant private max_boosted_proposals645 = 4096; //inject NONSTANDARD NAMING constructor(IERC20 _stakingToken) public { //The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS . //This will work for a network which already hosted the GEN token on this address (e.g mainnet). //If such contract address does not exist in the network (e.g ganache) //the contract will use the _stakingToken param as the //staking token address. if (address(gen_token_address929).ISCONTRACT51()) { stakingToken = IERC20(gen_token_address929); } else { stakingToken = _stakingToken; } } modifier VOTABLE853(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(_ISVOTABLE722(_proposalId)); _; } function PROPOSE661(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING external returns(bytes32) { // solhint-disable-next-line not-rely-on-time require(now > parameters[_paramsHash].activationTime, "not active yet"); //Check parameters existence. require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt = proposalsCnt.ADD15(1); // Open proposal: Proposal memory proposal; proposal.callbacks = msg.sender; proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization)); proposal.state = ProposalState.Queued; // solhint-disable-next-line not-rely-on-time proposal.times[0] = now;//submitted time proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = no391; proposal.paramsHash = _paramsHash; if (organizations[proposal.organizationId] == address(0)) { if (_organization == address(0)) { organizations[proposal.organizationId] = msg.sender; } else { organizations[proposal.organizationId] = _organization; } } //calc dao bounty uint256 daoBounty = parameters[_paramsHash].daoBountyConst.MUL295(averagesDownstakesOfBoosted[proposal.organizationId]).DIV1(100); if (daoBounty < parameters[_paramsHash].minimumDaoBounty) { proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty; } else { proposal.daoBountyRemain = daoBounty; } proposal.totalStakes = proposal.daoBountyRemain; proposals[proposalId] = proposal; proposals[proposalId].stakes[no391] = proposal.daoBountyRemain;//dao downstake on the proposal emit NEWPROPOSAL588(proposalId, organizations[proposal.organizationId], num_of_choices613, _proposer, _paramsHash); return proposalId; } function EXECUTEBOOSTED17(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod, "proposal state in not Boosted nor QuietEndingPeriod"); require(_EXECUTE501(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).ADD15(now.SUB141(proposal.currentBoostedVotePeriodLimit.ADD15(proposal.times[1])).DIV1(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100); require(stakingToken.TRANSFER985(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit EXPIRATIONCALLBOUNTY93(_proposalId, msg.sender, expirationCallBounty); } function SETPARAMETERS600( //inject NONSTANDARD NAMING uint[11] calldata _params, //use array here due to stack too deep issue. address _voteOnBehalf ) external returns(bytes32) { require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100"); require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000"); require(_params[7] <= 100, "votersReputationLossRatio <= 100"); require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[8] > 0, "minimumDaoBounty should be > 0"); require(_params[9] > 0, "daoBountyConst should be > 0"); bytes32 paramsHash = GETPARAMETERSHASH529(_params, _voteOnBehalf); //set a limit for power for a given alpha to prevent overflow uint256 limitExponent = 172;//for alpha less or equal 2 uint256 j = 2; for (uint256 i = 2000; i < 16000; i = i*2) { if ((_params[4] > i) && (_params[4] <= i*2)) { limitExponent = limitExponent/j; break; } j++; } parameters[paramsHash] = Parameters({ queuedVoteRequiredPercentage: _params[0], queuedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], preBoostedVotePeriodLimit: _params[3], thresholdConst:uint216(_params[4]).FRACTION401(uint216(1000)), limitExponentValue:limitExponent, quietEndingPeriod: _params[5], proposingRepReward: _params[6], votersReputationLossRatio:_params[7], minimumDaoBounty:_params[8], daoBountyConst:_params[9], activationTime:_params[10], voteOnBehalf:_voteOnBehalf }); return paramsHash; } // solhint-disable-next-line function-max-lines,code-complexity function REDEEM641(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue), "Proposal should be Executed or ExpiredInQueue"); Parameters memory params = parameters[proposal.paramsHash]; uint256 lostReputation; if (proposal.winningVote == yes596) { lostReputation = proposal.preBoostedVotes[no391]; } else { lostReputation = proposal.preBoostedVotes[yes596]; } lostReputation = (lostReputation.MUL295(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; uint256 totalStakes = proposal.stakes[no391].ADD15(proposal.stakes[yes596]); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; if (staker.amount > 0) { uint256 totalStakesLeftAfterCallBounty = totalStakes.SUB141(proposal.expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100)); if (proposal.state == ProposalState.ExpiredInQueue) { //Stakes of a proposal that expires in Queue are sent back to stakers rewards[0] = staker.amount; } else if (staker.vote == proposal.winningVote) { if (staker.vote == yes596) { if (proposal.daoBounty < totalStakesLeftAfterCallBounty) { uint256 _totalStakes = totalStakesLeftAfterCallBounty.SUB141(proposal.daoBounty); rewards[0] = (staker.amount.MUL295(_totalStakes))/totalWinningStakes; } } else { rewards[0] = (staker.amount.MUL295(totalStakesLeftAfterCallBounty))/totalWinningStakes; } } staker.amount = 0; } //dao redeem its winnings if (proposal.daoRedeemItsWinnings == false && _beneficiary == organizations[proposal.organizationId] && proposal.state != ProposalState.ExpiredInQueue && proposal.winningVote == no391) { rewards[0] = rewards[0].ADD15((proposal.daoBounty.MUL295(totalStakes))/totalWinningStakes).SUB141(proposal.daoBounty); proposal.daoRedeemItsWinnings = true; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0) && (voter.preBoosted)) { if (proposal.state == ProposalState.ExpiredInQueue) { //give back reputation for the voter rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100) .ADD15((voter.reputation.MUL295(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes596)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.SUB141(rewards[0]); require(stakingToken.TRANSFER985(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit REDEEM636(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].ADD15(rewards[2]) != 0) { VotingMachineCallbacksInterface(proposal.callbacks) .MINTREPUTATION981(rewards[1].ADD15(rewards[2]), _beneficiary, _proposalId); emit REDEEMREPUTATION314( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].ADD15(rewards[2]) ); } } function REDEEMDAOBOUNTY8(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING public returns(uint256 redeemedAmount, uint256 potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Executed); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; Staker storage staker = proposal.stakers[_beneficiary]; if ( (staker.amount4Bounty > 0)&& (staker.vote == proposal.winningVote)&& (proposal.winningVote == yes596)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (VotingMachineCallbacksInterface(proposal.callbacks) .BALANCEOFSTAKINGTOKEN878(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.SUB141(potentialAmount); require( VotingMachineCallbacksInterface(proposal.callbacks) .STAKINGTOKENTRANSFER53(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit REDEEMDAOBOUNTY578(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } function SHOULDBOOST603(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING Proposal memory proposal = proposals[_proposalId]; return (_SCORE635(_proposalId) > THRESHOLD53(proposal.paramsHash, proposal.organizationId)); } function THRESHOLD53(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.POW948(power); } function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING uint[11] memory _params,//use array here due to stack too deep issue. address _voteOnBehalf ) public pure returns(bytes32) { //double call to keccak256 to avoid deep stack issue when call with too many params. return keccak256( abi.encodePacked( keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10]) ), _voteOnBehalf )); } // solhint-disable-next-line function-max-lines,code-complexity function _EXECUTE501(bytes32 _proposalId) internal VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = VotingMachineCallbacksInterface(proposal.callbacks).GETTOTALREPUTATIONSUPPLY50(_proposalId); //first divide by 100 to prevent overflow uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage; ExecutionState executionState = ExecutionState.None; uint256 averageDownstakesOfBoosted; uint256 confidenceThreshold; if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. if (proposal.state == ProposalState.Queued) { executionState = ExecutionState.QueueBarCrossed; } else if (proposal.state == ProposalState.PreBoosted) { executionState = ExecutionState.PreBoostedBarCrossed; } else { executionState = ExecutionState.BoostedBarCrossed; } proposal.state = ProposalState.Executed; } else { if (proposal.state == ProposalState.Queued) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) { proposal.state = ProposalState.ExpiredInQueue; proposal.winningVote = no391; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId); if (_SCORE635(_proposalId) > confidenceThreshold) { //change proposal mode to PreBoosted mode. proposal.state = ProposalState.PreBoosted; // solhint-disable-next-line not-rely-on-time proposal.times[2] = now; proposal.confidenceThreshold = confidenceThreshold; } } } if (proposal.state == ProposalState.PreBoosted) { confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_SCORE635(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals645)) { //change proposal mode to Boosted mode. proposal.state = ProposalState.Boosted; // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; orgBoostedProposalsCnt[proposal.organizationId]++; //add a value to average -> average = average + ((value - average) / nbValues) averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; // solium-disable-next-line indentation averagesDownstakesOfBoosted[proposal.organizationId] = uint256(int256(averageDownstakesOfBoosted) + ((int256(proposal.stakes[no391])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _SCORE635(_proposalId); if (proposalScore <= proposal.confidenceThreshold.MIN317(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = confidenceThreshold; emit CONFIDENCELEVELCHANGE532(_proposalId, confidenceThreshold); } } } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) { proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } } if (executionState != ExecutionState.None) { if ((executionState == ExecutionState.BoostedTimeOut) || (executionState == ExecutionState.BoostedBarCrossed)) { orgBoostedProposalsCnt[tmpProposal.organizationId] = orgBoostedProposalsCnt[tmpProposal.organizationId].SUB141(1); //remove a value from average = ((average * nbValues) - value) / (nbValues - 1); uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId]; if (boostedProposals == 0) { averagesDownstakesOfBoosted[proposal.organizationId] = 0; } else { averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; averagesDownstakesOfBoosted[proposal.organizationId] = (averageDownstakesOfBoosted.MUL295(boostedProposals+1).SUB141(proposal.stakes[no391]))/boostedProposals; } } emit EXECUTEPROPOSAL706( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPEXECUTEPROPOSAL538(_proposalId, executionState); ProposalExecuteInterface(proposal.callbacks).EXECUTEPROPOSAL422(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit STATECHANGE374(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } function _STAKE234(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING // 0 is not a valid vote. require(_vote <= num_of_choices613 && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_EXECUTE501(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if ((proposal.state != ProposalState.PreBoosted) && (proposal.state != ProposalState.Queued)) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint256 amount = _amount; require(stakingToken.TRANSFERFROM649(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.ADD15(amount); //update totalRedeemableStakes staker.amount = staker.amount.ADD15(amount); //This is to prevent average downstakes calculation overflow //Note that any how GEN cap is 100000000 ether. require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high"); require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high"); if (_vote == yes596) { staker.amount4Bounty = staker.amount4Bounty.ADD15(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.ADD15(proposal.stakes[_vote]); emit STAKE754(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _EXECUTE501(_proposalId); } // solhint-disable-next-line function-max-lines,code-complexity function INTERNALVOTE757(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING require(_vote <= num_of_choices613 && _vote > 0, "0 < _vote <= 2"); if (_EXECUTE501(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).REPUTATIONOF984(_voter, _proposalId); require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.ADD15(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[no391] == proposal.votes[proposal.winningVote]) && proposal.winningVote == yes596)) { if (proposal.state == ProposalState.Boosted && // solhint-disable-next-line not-rely-on-time ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { //quietEndingPeriod if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.ADD15(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.MUL295(rep))/100; VotingMachineCallbacksInterface(proposal.callbacks).BURNREPUTATION898(reputationDeposit, _voter, _proposalId); } emit VOTEPROPOSAL760(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _EXECUTE501(_proposalId); } function _SCORE635(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return uint216(proposal.stakes[yes596]).FRACTION401(uint216(proposal.stakes[no391])); } function _ISVOTABLE722(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol pragma solidity ^0.5.4; contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic { using ECDSA for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant delegation_hash_eip712291 = //inject NONSTANDARD NAMING keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce constructor(IERC20 _stakingToken) public // solhint-disable-next-line no-empty-blocks GenesisProtocolLogic(_stakingToken) { } function STAKE53(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING return _STAKE234(_proposalId, _vote, _amount, msg.sender); } function STAKEWITHSIGNATURE42( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( delegation_hash_eip712291, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).TOETHSIGNEDMESSAGEHASH747(); } address staker = delegationDigest.RECOVER336(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].ADD15(1); return _STAKE234(_proposalId, _vote, _amount, staker); } function VOTE536(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING external VOTABLE853(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return INTERNALVOTE757(_proposalId, voter, _vote, _amount); } function CANCELVOTE202(bytes32 _proposalId) external VOTABLE853(_proposalId) { //inject NONSTANDARD NAMING //this is not allowed return; } function EXECUTE916(bytes32 _proposalId) external VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING return _EXECUTE501(_proposalId); } function GETNUMBEROFCHOICES589(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING return num_of_choices613; } function GETPROPOSALTIMES314(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING return proposals[_proposalId].times; } function VOTEINFO167(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].votes[_choice]; } function ISVOTABLE375(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING return _ISVOTABLE722(_proposalId); } function PROPOSALSTATUS186(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING return ( proposals[_proposalId].preBoostedVotes[yes596], proposals[_proposalId].preBoostedVotes[no391], proposals[_proposalId].stakes[yes596], proposals[_proposalId].stakes[no391] ); } function GETPROPOSALORGANIZATION49(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING return (proposals[_proposalId].organizationId); } function GETSTAKER814(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } function VOTESTAKE56(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].stakes[_vote]; } function WINNINGVOTE889(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].winningVote; } function STATE293(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING return proposals[_proposalId].state; } function ISABSTAINALLOW791() external pure returns(bool) { //inject NONSTANDARD NAMING return false; } function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING return (yes596, no391); } function SCORE81(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING return _SCORE635(_proposalId); } } // File: contracts/votingMachines/VotingMachineCallbacks.sol pragma solidity ^0.5.4; contract VotingMachineCallbacks is VotingMachineCallbacksInterface { struct ProposalInfo { uint256 blockNumber; // the proposal's block number Avatar avatar; // the proposal's avatar } modifier ONLYVOTINGMACHINE284(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine"); _; } // VotingMaching -> proposalId -> ProposalInfo mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo; function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).MINTREPUTATION981(_amount, _beneficiary, address(avatar)); } function BURNREPUTATION898(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).BURNREPUTATION898(_amount, _beneficiary, address(avatar)); } function STAKINGTOKENTRANSFER53( //inject NONSTANDARD NAMING IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).EXTERNALTOKENTRANSFER167(_stakingToken, _beneficiary, _amount, avatar); } function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) { return 0; } return _stakingToken.BALANCEOF995(address(avatar)); } function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().TOTALSUPPLYAT652(proposal.blockNumber); } function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().BALANCEOFAT780(_owner, proposal.blockNumber); } } // File: contracts/universalSchemes/SchemeRegistrar.sol pragma solidity ^0.5.4; contract SchemeRegistrar is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface { event NEWSCHEMEPROPOSAL971( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string _descriptionHash ); event REMOVESCHEMEPROPOSAL965(address indexed _avatar, //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, string _descriptionHash ); event PROPOSALEXECUTED934(address indexed _avatar, bytes32 indexed _proposalId, int256 _param); //inject NONSTANDARD NAMING event PROPOSALDELETED307(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING // a SchemeProposal is a proposal to add or remove a scheme to/from the an organization struct SchemeProposal { address scheme; // bool addScheme; // true: add a scheme, false: remove a scheme. bytes32 parametersHash; bytes4 permissions; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>SchemeProposal)) public organizationsProposals; // A mapping from hashes to parameters (use to store a particular configuration on the controller) struct Parameters { bytes32 voteRegisterParams; bytes32 voteRemoveParams; IntVoteInterface intVote; } mapping(bytes32=>Parameters) public parameters; function EXECUTEPROPOSAL422(bytes32 _proposalId, int256 _param) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.scheme != address(0)); delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED307(address(avatar), _proposalId); if (_param == 1) { // Define controller and get the params: ControllerInterface controller = ControllerInterface(avatar.OWNER574()); // Add a scheme: if (proposal.addScheme) { require(controller.REGISTERSCHEME37( proposal.scheme, proposal.parametersHash, proposal.permissions, address(avatar)) ); } // Remove a scheme: if (!proposal.addScheme) { require(controller.UNREGISTERSCHEME785(proposal.scheme, address(avatar))); } } emit PROPOSALEXECUTED934(address(avatar), _proposalId, _param); return true; } function SETPARAMETERS600( //inject NONSTANDARD NAMING bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public returns(bytes32) { bytes32 paramsHash = GETPARAMETERSHASH529(_voteRegisterParams, _voteRemoveParams, _intVote); parameters[paramsHash].voteRegisterParams = _voteRegisterParams; parameters[paramsHash].voteRemoveParams = _voteRemoveParams; parameters[paramsHash].intVote = _intVote; return paramsHash; } function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteRegisterParams, _voteRemoveParams, _intVote)); } function PROPOSESCHEME503( //inject NONSTANDARD NAMING Avatar _avatar, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string memory _descriptionHash ) public returns(bytes32) { // propose require(_scheme != address(0), "scheme cannot be zero"); Parameters memory controllerParams = parameters[GETPARAMETERSFROMCONTROLLER560(_avatar)]; bytes32 proposalId = controllerParams.intVote.PROPOSE661( 2, controllerParams.voteRegisterParams, msg.sender, address(_avatar) ); SchemeProposal memory proposal = SchemeProposal({ scheme: _scheme, parametersHash: _parametersHash, addScheme: true, permissions: _permissions }); emit NEWSCHEMEPROPOSAL971( address(_avatar), proposalId, address(controllerParams.intVote), _scheme, _parametersHash, _permissions, _descriptionHash ); organizationsProposals[address(_avatar)][proposalId] = proposal; proposalsInfo[address(controllerParams.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } function PROPOSETOREMOVESCHEME279(Avatar _avatar, address _scheme, string memory _descriptionHash) //inject NONSTANDARD NAMING public returns(bytes32) { require(_scheme != address(0), "scheme cannot be zero"); bytes32 paramsHash = GETPARAMETERSFROMCONTROLLER560(_avatar); Parameters memory params = parameters[paramsHash]; IntVoteInterface intVote = params.intVote; bytes32 proposalId = intVote.PROPOSE661(2, params.voteRemoveParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId].scheme = _scheme; emit REMOVESCHEMEPROPOSAL965(address(_avatar), proposalId, address(intVote), _scheme, _descriptionHash); proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } }
inject NONSTANDARD NAMING
function GETNUMBEROFCHOICES589(bytes32 _proposalId) external view returns(uint256);
15,855,582
./partial_match/42/0x714AdEedb372Ce1307D69ccA1DFc694A4Ec587Ed/sources/MyToken.sol
TODO: return how much `_spender` is allowed to spend on behalf of `_owner`
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { remaining = allowances[_owner][_spender]; return remaining; }
8,899,287
pragma solidity 0.6.11; // SPDX-License-Identifier: BSD-3-Clause /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || 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; } } /** * @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.0.0, only sets of type `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]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * @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); } } } } /** * @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. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface Token { function approve(address, uint) external returns (bool); function balanceOf(address) external view returns (uint); function transferFrom(address, address, uint) external returns (bool); function transfer(address, uint) external returns (bool); } interface OldIERC20 { function transfer(address, uint) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface 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; } /** * @dev Staking Smart Contract * * - Users stake Uniswap LP Tokens to receive WETH and DYP Tokens as Rewards * * - Reward Tokens (DYP) are added to contract balance upon deployment by deployer * * - After Adding the DYP rewards, admin is supposed to transfer ownership to Governance contract * * - Users deposit Set (Predecided) Uniswap LP Tokens and get a share of the farm * * - The smart contract disburses `disburseAmount` DYP as rewards over `disburseDuration` * * - A swap is attempted periodically at atleast a set delay from last swap * * - The swap is attempted according to SWAP_PATH for difference deployments of this contract * * - For 4 different deployments of this contract, the SWAP_PATH will be: * - DYP-WETH * - DYP-WBTC-WETH (assumes appropriate liquidity is available in WBTC-WETH pair) * - DYP-USDT-WETH (assumes appropriate liquidity is available in USDT-WETH pair) * - DYP-USDC-WETH (assumes appropriate liquidity is available in USDC-WETH pair) * * - Any swap may not have a price impact on DYP price of more than approx ~2.49% for the related DYP pair * DYP-WETH swap may not have a price impact of more than ~2.49% on DYP price in DYP-WETH pair * DYP-WBTC-WETH swap may not have a price impact of more than ~2.49% on DYP price in DYP-WBTC pair * DYP-USDT-WETH swap may not have a price impact of more than ~2.49% on DYP price in DYP-USDT pair * DYP-USDC-WETH swap may not have a price impact of more than ~2.49% on DYP price in DYP-USDC pair * * - After the swap,converted WETH is distributed to stakers at pro-rata basis, according to their share of the staking pool * on the moment when the WETH distribution is done. And remaining DYP is added to the amount to be distributed or burnt. * The remaining DYP are also attempted to be swapped to WETH in the next swap if the price impact is ~2.49% or less * * - At a set delay from last execution, Governance contract (owner) may execute disburse or burn features * * - Burn feature should send the DYP tokens to set BURN_ADDRESS * * - Disburse feature should disburse the DYP * (which would have a max price impact ~2.49% if it were to be swapped, at disburse time * - remaining DYP are sent to BURN_ADDRESS) * to stakers at pro-rata basis according to their share of * the staking pool at the moment the disburse is done * * - Users may claim their pending WETH and DYP anytime * * - Pending rewards are auto-claimed on any deposit or withdraw * * - Users need to wait `cliffTime` duration since their last deposit before withdrawing any LP Tokens * * - Owner may not transfer out LP Tokens from this contract anytime * * - Owner may transfer out WETH and DYP Tokens from this contract once `adminClaimableTime` is reached * * - CONTRACT VARIABLES must be changed to appropriate values before live deployment */ contract FarmProRata is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; using Address for address; // Contracts are not allowed to deposit, claim or withdraw modifier noContractsAllowed() { require(!(address(msg.sender).isContract()) && tx.origin == msg.sender, "No Contracts Allowed!"); _; } event RewardsTransferred(address holder, uint amount); event EthRewardsTransferred(address holder, uint amount); event RewardsDisbursed(uint amount); event EthRewardsDisbursed(uint amount); // ============ START CONTRACT VARIABLES ========================== // deposit token contract address and reward token contract address // these contracts (and uniswap pair & router) are "trusted" // and checked to not contain re-entrancy pattern // to safely avoid checks-effects-interactions where needed to simplify logic address public constant trustedDepositTokenAddress = 0x44B77e9cE8A20160290FcBAA44196744F354C1b7; address public constant trustedRewardTokenAddress = 0x961C8c0B1aaD0c0b10a51FeF6a867E3091BCef17; // Make sure to double-check BURN_ADDRESS address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; // cliffTime - withdraw is not possible within cliffTime of deposit uint public constant cliffTime = 3 days; // Amount of tokens uint public constant disburseAmount = 360000e18; // To be disbursed continuously over this duration uint public constant disburseDuration = 365 days; // If there are any undistributed or unclaimed tokens left in contract after this time // Admin can claim them uint public constant adminCanClaimAfter = 395 days; // delays between attempted swaps uint public constant swapAttemptPeriod = 1 days; // delays between attempted burns or token disbursement uint public constant burnOrDisburseTokensPeriod = 7 days; // do not change this => disburse 100% rewards over `disburseDuration` uint public constant disbursePercentX100 = 100e2; uint public constant MAGIC_NUMBER = 6289308176100628; // slippage tolerance uint public constant SLIPPAGE_TOLERANCE_X_100 = 100; // ============ END CONTRACT VARIABLES ========================== uint public contractDeployTime; uint public adminClaimableTime; uint public lastDisburseTime; uint public lastSwapExecutionTime; uint public lastBurnOrTokenDistributeTime; IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Pair public uniswapV2Pair; address[] public SWAP_PATH; constructor(address[] memory swapPath) public { contractDeployTime = now; adminClaimableTime = contractDeployTime.add(adminCanClaimAfter); lastDisburseTime = contractDeployTime; lastSwapExecutionTime = lastDisburseTime; lastBurnOrTokenDistributeTime = lastDisburseTime; uniswapRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Pair(trustedDepositTokenAddress); SWAP_PATH = swapPath; } uint public totalClaimedRewards = 0; uint public totalClaimedRewardsEth = 0; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public depositTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; mapping (address => uint) public totalEarnedEth; mapping (address => uint) public lastDivPoints; mapping (address => uint) public lastEthDivPoints; uint public contractBalance = 0; uint public totalDivPoints = 0; uint public totalEthDivPoints = 0; uint public totalTokens = 0; uint public tokensToBeDisbursedOrBurnt = 0; uint public tokensToBeSwapped = 0; uint internal constant pointMultiplier = 1e18; // To be executed by admin after deployment to add DYP to contract function addContractBalance(uint amount) public onlyOwner { require(Token(trustedRewardTokenAddress).transferFrom(msg.sender, address(this), amount), "Cannot add balance!"); contractBalance = contractBalance.add(amount); } // Private function to update account information and auto-claim pending rewards function updateAccount(address account) private { disburseTokens(); attemptSwap(); uint pendingDivs = getPendingDivs(account); if (pendingDivs > 0) { require(Token(trustedRewardTokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(account, pendingDivs); } uint pendingDivsEth = getPendingDivsEth(account); if (pendingDivsEth > 0) { require(Token(uniswapRouterV2.WETH()).transfer(account, pendingDivsEth), "Could not transfer WETH!"); totalEarnedEth[account] = totalEarnedEth[account].add(pendingDivsEth); totalClaimedRewardsEth = totalClaimedRewardsEth.add(pendingDivsEth); emit EthRewardsTransferred(account, pendingDivsEth); } lastClaimedTime[account] = now; lastDivPoints[account] = totalDivPoints; lastEthDivPoints[account] = totalEthDivPoints; } // view function to check last updated DYP pending rewards function getPendingDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint newDivPoints = totalDivPoints.sub(lastDivPoints[_holder]); uint depositedAmount = depositedTokens[_holder]; uint pendingDivs = depositedAmount.mul(newDivPoints).div(pointMultiplier); return pendingDivs; } // view function to check last updated WETH pending rewards function getPendingDivsEth(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint newDivPoints = totalEthDivPoints.sub(lastEthDivPoints[_holder]); uint depositedAmount = depositedTokens[_holder]; uint pendingDivs = depositedAmount.mul(newDivPoints).div(pointMultiplier); return pendingDivs; } // view functon to get number of stakers function getNumberOfHolders() public view returns (uint) { return holders.length(); } // deposit function to stake LP Tokens function deposit(uint amountToDeposit) public noContractsAllowed { require(amountToDeposit > 0, "Cannot deposit 0 Tokens"); updateAccount(msg.sender); require(Token(trustedDepositTokenAddress).transferFrom(msg.sender, address(this), amountToDeposit), "Insufficient Token Allowance"); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToDeposit); totalTokens = totalTokens.add(amountToDeposit); if (!holders.contains(msg.sender)) { holders.add(msg.sender); } depositTime[msg.sender] = now; } // withdraw function to unstake LP Tokens function withdraw(uint amountToWithdraw) public noContractsAllowed { require(amountToWithdraw > 0, "Cannot withdraw 0 Tokens!"); require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(depositTime[msg.sender]) > cliffTime, "You recently deposited, please wait before withdrawing."); updateAccount(msg.sender); require(Token(trustedDepositTokenAddress).transfer(msg.sender, amountToWithdraw), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); totalTokens = totalTokens.sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } // withdraw without caring about Rewards function emergencyWithdraw(uint amountToWithdraw) public noContractsAllowed { require(amountToWithdraw > 0, "Cannot withdraw 0 Tokens!"); require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(depositTime[msg.sender]) > cliffTime, "You recently deposited, please wait before withdrawing."); // manual update account here without withdrawing pending rewards disburseTokens(); // do not attempt swap here lastClaimedTime[msg.sender] = now; lastDivPoints[msg.sender] = totalDivPoints; lastEthDivPoints[msg.sender] = totalEthDivPoints; require(Token(trustedDepositTokenAddress).transfer(msg.sender, amountToWithdraw), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); totalTokens = totalTokens.sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } // claim function to claim pending rewards function claim() public noContractsAllowed { updateAccount(msg.sender); } // private function to distribute DYP rewards function distributeDivs(uint amount) private { require(amount > 0 && totalTokens > 0, "distributeDivs failed!"); totalDivPoints = totalDivPoints.add(amount.mul(pointMultiplier).div(totalTokens)); emit RewardsDisbursed(amount); } // private function to distribute WETH rewards function distributeDivsEth(uint amount) private { require(amount > 0 && totalTokens > 0, "distributeDivsEth failed!"); totalEthDivPoints = totalEthDivPoints.add(amount.mul(pointMultiplier).div(totalTokens)); emit EthRewardsDisbursed(amount); } // private function to allocate DYP to be disbursed calculated according to time passed function disburseTokens() private { uint amount = getPendingDisbursement(); if (contractBalance < amount) { amount = contractBalance; } if (amount == 0 || totalTokens == 0) return; tokensToBeSwapped = tokensToBeSwapped.add(amount); contractBalance = contractBalance.sub(amount); lastDisburseTime = now; } function attemptSwap() private { doSwap(); } function doSwap() private { // do not attemptSwap if no one has staked if (totalTokens == 0) { return; } // Cannot execute swap so quickly if (now.sub(lastSwapExecutionTime) < swapAttemptPeriod) { return; } // force reserves to match balances uniswapV2Pair.sync(); uint _tokensToBeSwapped = tokensToBeSwapped.add(tokensToBeDisbursedOrBurnt); uint maxSwappableAmount = getMaxSwappableAmount(); // don't proceed if no liquidity if (maxSwappableAmount == 0) return; if (maxSwappableAmount < tokensToBeSwapped) { uint diff = tokensToBeSwapped.sub(maxSwappableAmount); _tokensToBeSwapped = tokensToBeSwapped.sub(diff); tokensToBeDisbursedOrBurnt = tokensToBeDisbursedOrBurnt.add(diff); tokensToBeSwapped = 0; } else if (maxSwappableAmount < _tokensToBeSwapped) { uint diff = _tokensToBeSwapped.sub(maxSwappableAmount); _tokensToBeSwapped = _tokensToBeSwapped.sub(diff); tokensToBeDisbursedOrBurnt = diff; tokensToBeSwapped = 0; } else { tokensToBeSwapped = 0; tokensToBeDisbursedOrBurnt = 0; } // don't execute 0 swap tokens if (_tokensToBeSwapped == 0) { return; } // cannot execute swap at insufficient balance if (Token(trustedRewardTokenAddress).balanceOf(address(this)) < _tokensToBeSwapped) { return; } require(Token(trustedRewardTokenAddress).approve(address(uniswapRouterV2), _tokensToBeSwapped), 'approve failed!'); uint oldWethBalance = Token(uniswapRouterV2.WETH()).balanceOf(address(this)); uint amountOutMin; uint estimatedAmountOut = uniswapRouterV2.getAmountsOut(_tokensToBeSwapped, SWAP_PATH)[SWAP_PATH.length.sub(1)]; amountOutMin = estimatedAmountOut.mul(uint(100e2).sub(SLIPPAGE_TOLERANCE_X_100)).div(100e2); uniswapRouterV2.swapExactTokensForTokens(_tokensToBeSwapped, amountOutMin, SWAP_PATH, address(this), block.timestamp); uint newWethBalance = Token(uniswapRouterV2.WETH()).balanceOf(address(this)); uint wethReceived = newWethBalance.sub(oldWethBalance); require(wethReceived >= amountOutMin, "Invalid SWAP!"); if (wethReceived > 0) { distributeDivsEth(wethReceived); } lastSwapExecutionTime = now; } // Owner is supposed to be a Governance Contract function disburseRewardTokens() public onlyOwner { require(now.sub(lastBurnOrTokenDistributeTime) > burnOrDisburseTokensPeriod, "Recently executed, Please wait!"); // force reserves to match balances uniswapV2Pair.sync(); uint maxSwappableAmount = getMaxSwappableAmount(); uint _tokensToBeDisbursed = tokensToBeDisbursedOrBurnt; uint _tokensToBeBurnt; if (maxSwappableAmount < _tokensToBeDisbursed) { _tokensToBeBurnt = _tokensToBeDisbursed.sub(maxSwappableAmount); _tokensToBeDisbursed = maxSwappableAmount; } distributeDivs(_tokensToBeDisbursed); if (_tokensToBeBurnt > 0) { require(Token(trustedRewardTokenAddress).transfer(BURN_ADDRESS, _tokensToBeBurnt), "disburseRewardTokens: burn failed!"); } tokensToBeDisbursedOrBurnt = 0; lastBurnOrTokenDistributeTime = now; } // Owner is suposed to be a Governance Contract function burnRewardTokens() public onlyOwner { require(now.sub(lastBurnOrTokenDistributeTime) > burnOrDisburseTokensPeriod, "Recently executed, Please wait!"); require(Token(trustedRewardTokenAddress).transfer(BURN_ADDRESS, tokensToBeDisbursedOrBurnt), "burnRewardTokens failed!"); tokensToBeDisbursedOrBurnt = 0; lastBurnOrTokenDistributeTime = now; } // get token amount which has a max price impact of 2.5% for sells // !!IMPORTANT!! => Any functions using return value from this // MUST call `sync` on the pair before calling this function! function getMaxSwappableAmount() public view returns (uint) { uint tokensAvailable = Token(trustedRewardTokenAddress).balanceOf(trustedDepositTokenAddress); uint maxSwappableAmount = tokensAvailable.mul(MAGIC_NUMBER).div(1e18); return maxSwappableAmount; } // view function to calculate amount of DYP pending to be allocated since `lastDisburseTime` function getPendingDisbursement() public view returns (uint) { uint timeDiff; uint _now = now; uint _stakingEndTime = contractDeployTime.add(disburseDuration); if (_now > _stakingEndTime) { _now = _stakingEndTime; } if (lastDisburseTime >= _now) { timeDiff = 0; } else { timeDiff = _now.sub(lastDisburseTime); } uint pendingDisburse = disburseAmount .mul(disbursePercentX100) .mul(timeDiff) .div(disburseDuration) .div(10000); return pendingDisburse; } // view function to get depositors list function getDepositorsList(uint startIndex, uint endIndex) public view returns (address[] memory stakers, uint[] memory stakingTimestamps, uint[] memory lastClaimedTimeStamps, uint[] memory stakedTokens) { require (startIndex < endIndex); uint length = endIndex.sub(startIndex); address[] memory _stakers = new address[](length); uint[] memory _stakingTimestamps = new uint[](length); uint[] memory _lastClaimedTimeStamps = new uint[](length); uint[] memory _stakedTokens = new uint[](length); for (uint i = startIndex; i < endIndex; i = i.add(1)) { address staker = holders.at(i); uint listIndex = i.sub(startIndex); _stakers[listIndex] = staker; _stakingTimestamps[listIndex] = depositTime[staker]; _lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker]; _stakedTokens[listIndex] = depositedTokens[staker]; } return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens); } // function to allow owner to claim *other* modern ERC20 tokens sent to this contract function transferAnyERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner { require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out deposit tokens from this vault!"); require((_tokenAddr != trustedRewardTokenAddress && _tokenAddr != uniswapRouterV2.WETH()) || (now > adminClaimableTime), "Admin cannot Transfer out Reward Tokens or WETH Yet!"); require(Token(_tokenAddr).transfer(_to, _amount), "Could not transfer out tokens!"); } // function to allow owner to claim *other* legacy ERC20 tokens sent to this contract function transferAnyOldERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner { require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out deposit tokens from this vault!"); require((_tokenAddr != trustedRewardTokenAddress && _tokenAddr != uniswapRouterV2.WETH()) || (now > adminClaimableTime), "Admin cannot Transfer out Reward Tokens or WETH Yet!"); OldIERC20(_tokenAddr).transfer(_to, _amount); } }
function to allow owner to claim other legacy ERC20 tokens sent to this contract
function transferAnyOldERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner { require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out deposit tokens from this vault!"); require((_tokenAddr != trustedRewardTokenAddress && _tokenAddr != uniswapRouterV2.WETH()) || (now > adminClaimableTime), "Admin cannot Transfer out Reward Tokens or WETH Yet!"); OldIERC20(_tokenAddr).transfer(_to, _amount); }
1,114,825
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./libraries/SafeMath.sol"; contract HDS { using SafeMath for uint256; /// @notice EIP-20 token name for this token string public constant name = "Hades governance token"; /// @notice EIP-20 token symbol for this token string public constant symbol = "HDS"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 8; /// @notice Total number of tokens in circulation uint256 public totalSupply; /// @notice Max supply of tokens uint256 public constant maxSupply = 21000000e8; // 21 million /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint256)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint256) 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; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The admin address that have the auth to initialize the superior address public admin; /// @notice The distributor address that have the auth to mint or burn tokens address public superior; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, 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); /// @notice For safety auditor: the superior should be the deployed MarketController contract address modifier onlySuperior { require(superior == msg.sender, "HDS/permission denied"); _; } constructor() public { admin = msg.sender; uint256 initialSupply = 4200000e8; // 4.2 million balances[admin] = initialSupply; totalSupply = initialSupply; } function initialize(address _superior) external { require(admin == msg.sender, "HDS/permission denied"); require(superior == address(0), "HDS/Already initialized"); superior = _superior; } /** * @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 amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address owner = msg.sender; require(spender != address(0), "HDS/approve to zero address"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); return true; } /** * @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 amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool) { return transferFrom(msg.sender, dst, amount); } /** * @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 amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) public returns (bool) { require(balances[src] >= amount, "HDS/insufficient-balance"); require(src != address(0), "HDS/transfer from zero address"); require(dst != address(0), "HDS/transfer to zero address"); address sender = msg.sender; uint256 allowed = allowances[src][sender]; if (sender != src && allowed != uint256(-1)) { require(allowed >= amount, "HDS/insufficient-allowance"); allowances[src][sender] = allowed.sub(amount); emit Approval(src, sender, allowances[src][sender]); } balances[src] = balances[src].sub(amount); balances[dst] = balances[dst].add(amount); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); return true; } /** * @notice Mint `amount` tokens for 'src' * @param src The address to receive the mint tokens * @param amount The number of tokens to mint */ function mint(address src, uint256 amount) external onlySuperior { require(totalSupply.add(amount) <= maxSupply, "HDS/Max supply exceeded"); require(src != address(0), "HDS/mint to zero address"); balances[src] = balances[src].add(amount); totalSupply = totalSupply.add(amount); emit Transfer(address(0), src, amount); } /** * @notice Burn `amount` tokens for 'src' * @param src The address to burn tokens * @param amount The number of tokens to burn */ function burn(address src, uint256 amount) external { require(balances[src] >= amount, "HDS/insufficient-balance"); require(src != address(0), "HDS/burn from zero address"); address sender = msg.sender; uint256 allowed = allowances[src][sender]; if (src != sender && allowed != uint256(-1)) { require(allowed >= amount, "HDS/insufficient-allowance"); allowances[src][sender] = allowed.sub(amount); emit Approval(src, sender, allowances[src][sender]); } balances[src] = balances[src].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(src, address(0), amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { 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 ) public { 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), "HDS/ invalid signature"); require(nonce == nonces[signatory]++, "HDS/ invalid nonce"); require(now <= expiry, "HDS/signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "HDS/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]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, balances[delegator]); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { 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)) { 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, "HDS/Block number overflow"); 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; } }
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { 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), "HDS/ invalid signature"); require(nonce == nonces[signatory]++, "HDS/ invalid nonce"); require(now <= expiry, "HDS/signature expired"); return _delegate(signatory, delegatee); }
13,089,599
./full_match/1/0x8c2EeE9d6422b6D998667761aC77ba43b05C44d6/sources/contracts/ZeusNFTProd.sol
-----TRANSFERS FUNCTIONS-----
function transferFrom(address from, address to, uint256 tokenId) public payable override(ERC721A, IERC721A) onlyAllowedOperator(from) { super.transferFrom(from, to, tokenId); }
2,976,286
./partial_match/97/0xBE2870d1dE8c30D31388fb1e86c209d85f0e8866/sources/AnimalFactory.sol
The structure defining a single animal
{ struct AnimalProperties { uint id; string name; string desc; bool upForSale; uint priceForSale; bool upForMating; bool eggPhase; uint priceForMating; bool isBornByMating; uint parentId1; uint parentId2; uint birthdate; uint AssetsId; uint generationId; uint cuteVotes; uint gameVotes; } using SafeMath for uint256; uint public priceForBuyingAssets = 0.25 ether; uint public priceForSaleAdvertisement = 0.025 ether; uint public priceForSuccessfulSale = 0.05 ether; uint public ownerPerThousandShareForBuying = 5; uint[] eggPhaseAnimalIds; uint[] animalIdsWithPendingAssetss; ERC721Interface public token; uint uniqueAnimalId=0; mapping(uint=>AnimalProperties) animalAgainstId; mapping(uint=>uint[]) childrenIdAgainstAnimalId; uint[] upForMatingList; uint[] upForSaleList; address[] memberAddresses; AnimalProperties animalObject; uint public totalAnimalsMax = 10000; uint public freeAnimalsLimit = 4; bool public isContractPaused; bool public isMintingPaused; bool public isMatingPaused; uint256 public weiPerAnimal = 0.25 ether; uint public priceForMateAdvertisement = 0.025 ether; uint public ownerPerThousandShareForMating = 2; uint256 public weiRaised; uint256 public totalAnimalsCreated=0; event AnimalsPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function AnimalFactory(address _walletOwner,address _tokenAddress) public { require(_walletOwner != 0x0); owner = _walletOwner; isContractPaused = false; isMintingPaused = false; isMatingPaused = true; priceForMateAdvertisement = 0.025 ether; priceForSaleAdvertisement = 0.025 ether; priceForBuyingAssets = 0.25 ether; token = ERC721Interface(_tokenAddress); } function getAnimalById(uint aid) public constant returns (string, string,uint,uint ,uint, uint,uint) { if(animalAgainstId[aid].eggPhase==true) { return(animalAgainstId[aid].name, animalAgainstId[aid].desc, 2**256 - 1, animalAgainstId[aid].priceForSale, animalAgainstId[aid].priceForMating, animalAgainstId[aid].parentId1, animalAgainstId[aid].parentId2 ); } else { return(animalAgainstId[aid].name, animalAgainstId[aid].desc, animalAgainstId[aid].id, animalAgainstId[aid].priceForSale, animalAgainstId[aid].priceForMating, animalAgainstId[aid].parentId1, animalAgainstId[aid].parentId2 ); } } function getAnimalById(uint aid) public constant returns (string, string,uint,uint ,uint, uint,uint) { if(animalAgainstId[aid].eggPhase==true) { return(animalAgainstId[aid].name, animalAgainstId[aid].desc, 2**256 - 1, animalAgainstId[aid].priceForSale, animalAgainstId[aid].priceForMating, animalAgainstId[aid].parentId1, animalAgainstId[aid].parentId2 ); } else { return(animalAgainstId[aid].name, animalAgainstId[aid].desc, animalAgainstId[aid].id, animalAgainstId[aid].priceForSale, animalAgainstId[aid].priceForMating, animalAgainstId[aid].parentId1, animalAgainstId[aid].parentId2 ); } } function getAnimalById(uint aid) public constant returns (string, string,uint,uint ,uint, uint,uint) { if(animalAgainstId[aid].eggPhase==true) { return(animalAgainstId[aid].name, animalAgainstId[aid].desc, 2**256 - 1, animalAgainstId[aid].priceForSale, animalAgainstId[aid].priceForMating, animalAgainstId[aid].parentId1, animalAgainstId[aid].parentId2 ); } else { return(animalAgainstId[aid].name, animalAgainstId[aid].desc, animalAgainstId[aid].id, animalAgainstId[aid].priceForSale, animalAgainstId[aid].priceForMating, animalAgainstId[aid].parentId1, animalAgainstId[aid].parentId2 ); } } function getAnimalByIdVisibility(uint aid) public constant returns (bool upforsale,bool upformating,bool eggphase,bool isbornbymating, uint birthdate, uint Assetsid, uint generationid ) { return( animalAgainstId[aid].upForSale, animalAgainstId[aid].upForMating, animalAgainstId[aid].eggPhase, animalAgainstId[aid].isBornByMating, animalAgainstId[aid].birthdate, animalAgainstId[aid].AssetsId, animalAgainstId[aid].generationId ); } function getOwnerByAnimalId(uint aid) public constant returns (address) { return token.ownerOf(aid); } function getAllAnimalsByAddress(address ad) public constant returns (uint[] listAnimals) { require (!isContractPaused); return token.getAnimalIdAgainstAddress(ad); } function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable { require (!isContractPaused); require (!isMintingPaused); require(validPurchase()); require(msg.sender != 0x0); if (msg.sender!=owner) { require(msg.value>=weiPerAnimal); } require(msg.value>=weiPerAnimal); if (totalAnimalsCreated >= totalAnimalsMax) throw; uint gId=0; { gId=1; } uint256 weiAmount = msg.value; uniqueAnimalId++; animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: false, priceForMating:0, isBornByMating:false, parentId1:0, parentId2:0, birthdate:now, AssetsId:0, generationId:gId, cuteVotes:0, gameVotes:0 }); emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens); totalAnimalsCreated++; } function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable { require (!isContractPaused); require (!isMintingPaused); require(validPurchase()); require(msg.sender != 0x0); if (msg.sender!=owner) { require(msg.value>=weiPerAnimal); } require(msg.value>=weiPerAnimal); if (totalAnimalsCreated >= totalAnimalsMax) throw; uint gId=0; { gId=1; } uint256 weiAmount = msg.value; uniqueAnimalId++; animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: false, priceForMating:0, isBornByMating:false, parentId1:0, parentId2:0, birthdate:now, AssetsId:0, generationId:gId, cuteVotes:0, gameVotes:0 }); emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens); totalAnimalsCreated++; } if (msg.sender!=owner) function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable { require (!isContractPaused); require (!isMintingPaused); require(validPurchase()); require(msg.sender != 0x0); if (msg.sender!=owner) { require(msg.value>=weiPerAnimal); } require(msg.value>=weiPerAnimal); if (totalAnimalsCreated >= totalAnimalsMax) throw; uint gId=0; { gId=1; } uint256 weiAmount = msg.value; uniqueAnimalId++; animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: false, priceForMating:0, isBornByMating:false, parentId1:0, parentId2:0, birthdate:now, AssetsId:0, generationId:gId, cuteVotes:0, gameVotes:0 }); emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens); totalAnimalsCreated++; } uint256 tokens = weiAmount.div(weiPerAnimal); weiRaised = weiRaised.add(weiAmount); function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable { require (!isContractPaused); require (!isMintingPaused); require(validPurchase()); require(msg.sender != 0x0); if (msg.sender!=owner) { require(msg.value>=weiPerAnimal); } require(msg.value>=weiPerAnimal); if (totalAnimalsCreated >= totalAnimalsMax) throw; uint gId=0; { gId=1; } uint256 weiAmount = msg.value; uniqueAnimalId++; animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: false, priceForMating:0, isBornByMating:false, parentId1:0, parentId2:0, birthdate:now, AssetsId:0, generationId:gId, cuteVotes:0, gameVotes:0 }); emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens); totalAnimalsCreated++; } token.sendToken(msg.sender, uniqueAnimalId,animalName); animalAgainstId[uniqueAnimalId]=animalObject; owner.transfer(msg.value); function buyAnimalsFromUser(uint animalId) public payable { require (!isContractPaused); require(msg.sender != 0x0); address prevOwner=token.ownerOf(animalId); require(prevOwner!=msg.sender); uint price=animalAgainstId[animalId].priceForSale; uint convertedpricetoEther = msg.value; uint OwnerPercentage=animalAgainstId[animalId].priceForSale.mul(ownerPerThousandShareForBuying); OwnerPercentage=OwnerPercentage.div(1000); uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale.sub(OwnerPercentage); require(convertedpricetoEther>=price); token.safeTransferFrom(prevOwner,msg.sender,animalId); animalAgainstId[animalId].upForSale=false; animalAgainstId[animalId].priceForSale=0; for (uint j=0;j<upForSaleList.length;j++) { if (upForSaleList[j] == animalId) delete upForSaleList[j]; } } function buyAnimalsFromUser(uint animalId) public payable { require (!isContractPaused); require(msg.sender != 0x0); address prevOwner=token.ownerOf(animalId); require(prevOwner!=msg.sender); uint price=animalAgainstId[animalId].priceForSale; uint convertedpricetoEther = msg.value; uint OwnerPercentage=animalAgainstId[animalId].priceForSale.mul(ownerPerThousandShareForBuying); OwnerPercentage=OwnerPercentage.div(1000); uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale.sub(OwnerPercentage); require(convertedpricetoEther>=price); token.safeTransferFrom(prevOwner,msg.sender,animalId); animalAgainstId[animalId].upForSale=false; animalAgainstId[animalId].priceForSale=0; for (uint j=0;j<upForSaleList.length;j++) { if (upForSaleList[j] == animalId) delete upForSaleList[j]; } } prevOwner.transfer(price); owner.transfer(OwnerPercentage); function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable { require (!isContractPaused); require(!isMatingPaused); require(msg.sender != 0x0); require (token.ownerOf(parent2Id) == msg.sender); require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id)); require(animalAgainstId[parent1Id].upForMating==true); uint convertedpricetoEther = msg.value; uint price=animalAgainstId[parent1Id].priceForMating; uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating); OwnerPercentage=OwnerPercentage.div(1000); uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage); require(convertedpricetoEther>=price); uint generationnum = 1; if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId) { generationnum = animalAgainstId[parent1Id].generationId+1; } else{ generationnum = animalAgainstId[parent2Id].generationId+1; } animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: true, priceForMating:0, isBornByMating:true, parentId1: parent1Id, parentId2: parent2Id, birthdate:now, AssetsId:0, generationId:generationnum, cuteVotes:0, gameVotes:0 }); childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId); { if (upForMatingList[i]==parent1Id) delete upForMatingList[i]; } animalAgainstId[parent1Id].priceForMating = 0; } function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable { require (!isContractPaused); require(!isMatingPaused); require(msg.sender != 0x0); require (token.ownerOf(parent2Id) == msg.sender); require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id)); require(animalAgainstId[parent1Id].upForMating==true); uint convertedpricetoEther = msg.value; uint price=animalAgainstId[parent1Id].priceForMating; uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating); OwnerPercentage=OwnerPercentage.div(1000); uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage); require(convertedpricetoEther>=price); uint generationnum = 1; if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId) { generationnum = animalAgainstId[parent1Id].generationId+1; } else{ generationnum = animalAgainstId[parent2Id].generationId+1; } animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: true, priceForMating:0, isBornByMating:true, parentId1: parent1Id, parentId2: parent2Id, birthdate:now, AssetsId:0, generationId:generationnum, cuteVotes:0, gameVotes:0 }); childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId); { if (upForMatingList[i]==parent1Id) delete upForMatingList[i]; } animalAgainstId[parent1Id].priceForMating = 0; } function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable { require (!isContractPaused); require(!isMatingPaused); require(msg.sender != 0x0); require (token.ownerOf(parent2Id) == msg.sender); require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id)); require(animalAgainstId[parent1Id].upForMating==true); uint convertedpricetoEther = msg.value; uint price=animalAgainstId[parent1Id].priceForMating; uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating); OwnerPercentage=OwnerPercentage.div(1000); uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage); require(convertedpricetoEther>=price); uint generationnum = 1; if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId) { generationnum = animalAgainstId[parent1Id].generationId+1; } else{ generationnum = animalAgainstId[parent2Id].generationId+1; } animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: true, priceForMating:0, isBornByMating:true, parentId1: parent1Id, parentId2: parent2Id, birthdate:now, AssetsId:0, generationId:generationnum, cuteVotes:0, gameVotes:0 }); childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId); { if (upForMatingList[i]==parent1Id) delete upForMatingList[i]; } animalAgainstId[parent1Id].priceForMating = 0; } uniqueAnimalId++; function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable { require (!isContractPaused); require(!isMatingPaused); require(msg.sender != 0x0); require (token.ownerOf(parent2Id) == msg.sender); require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id)); require(animalAgainstId[parent1Id].upForMating==true); uint convertedpricetoEther = msg.value; uint price=animalAgainstId[parent1Id].priceForMating; uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating); OwnerPercentage=OwnerPercentage.div(1000); uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage); require(convertedpricetoEther>=price); uint generationnum = 1; if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId) { generationnum = animalAgainstId[parent1Id].generationId+1; } else{ generationnum = animalAgainstId[parent2Id].generationId+1; } animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: true, priceForMating:0, isBornByMating:true, parentId1: parent1Id, parentId2: parent2Id, birthdate:now, AssetsId:0, generationId:generationnum, cuteVotes:0, gameVotes:0 }); childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId); { if (upForMatingList[i]==parent1Id) delete upForMatingList[i]; } animalAgainstId[parent1Id].priceForMating = 0; } token.sendToken(msg.sender,uniqueAnimalId,animalName); animalAgainstId[uniqueAnimalId]=animalObject; eggPhaseAnimalIds.push(uniqueAnimalId); childrenIdAgainstAnimalId[parent1Id].push(uniqueAnimalId); for (uint i=0;i<upForMatingList.length;i++) function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable { require (!isContractPaused); require(!isMatingPaused); require(msg.sender != 0x0); require (token.ownerOf(parent2Id) == msg.sender); require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id)); require(animalAgainstId[parent1Id].upForMating==true); uint convertedpricetoEther = msg.value; uint price=animalAgainstId[parent1Id].priceForMating; uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating); OwnerPercentage=OwnerPercentage.div(1000); uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage); require(convertedpricetoEther>=price); uint generationnum = 1; if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId) { generationnum = animalAgainstId[parent1Id].generationId+1; } else{ generationnum = animalAgainstId[parent2Id].generationId+1; } animalObject = AnimalProperties({ id:uniqueAnimalId, name:animalName, desc:animalDesc, upForSale: false, priceForSale:0, upForMating: false, eggPhase: true, priceForMating:0, isBornByMating:true, parentId1: parent1Id, parentId2: parent2Id, birthdate:now, AssetsId:0, generationId:generationnum, cuteVotes:0, gameVotes:0 }); childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId); { if (upForMatingList[i]==parent1Id) delete upForMatingList[i]; } animalAgainstId[parent1Id].priceForMating = 0; } animalAgainstId[parent1Id].upForMating = false; token.ownerOf(parent1Id).transfer(price); owner.transfer(OwnerPercentage); function TransferAnimalToAnotherUser(uint animalId,address to) public { require (!isContractPaused); require(msg.sender != 0x0); require(token.ownerOf(animalId)==msg.sender); require(animalAgainstId[animalId].upForSale == false); require(animalAgainstId[animalId].upForMating == false); token.safeTransferFrom(msg.sender, to, animalId); } function voteGame(uint animalId, uint gamepoints) { require(msg.sender != 0x0); animalAgainstId[animalId].gameVotes.add(1); } function voteGameMinus(uint animalId, uint gamepoints) { require(msg.sender != 0x0); animalAgainstId[animalId].gameVotes.sub(1); } function voteCuteness(uint animalId, uint vote) { require(msg.sender != 0x0); animalAgainstId[animalId].cuteVotes.add(1); } function putSaleRequest(uint animalId, uint salePrice) public payable { require (!isContractPaused); uint convertedpricetoEther = salePrice; if (msg.sender!=owner) { require(msg.value>=priceForSaleAdvertisement); } animalAgainstId[animalId].priceForSale=convertedpricetoEther; upForSaleList.push(animalId); } function putSaleRequest(uint animalId, uint salePrice) public payable { require (!isContractPaused); uint convertedpricetoEther = salePrice; if (msg.sender!=owner) { require(msg.value>=priceForSaleAdvertisement); } animalAgainstId[animalId].priceForSale=convertedpricetoEther; upForSaleList.push(animalId); } require(token.ownerOf(animalId)==msg.sender); require(animalAgainstId[animalId].eggPhase==false); require(animalAgainstId[animalId].upForSale==false); require(animalAgainstId[animalId].upForMating==false); animalAgainstId[animalId].upForSale=true; owner.transfer(msg.value); function withdrawSaleRequest(uint animalId) public { require (!isContractPaused); require(token.ownerOf(animalId)==msg.sender); require(animalAgainstId[animalId].upForSale==true); animalAgainstId[animalId].upForSale=false; animalAgainstId[animalId].priceForSale=0; for (uint i=0;i<upForSaleList.length;i++) { if (upForSaleList[i]==animalId) delete upForSaleList[i]; } } function withdrawSaleRequest(uint animalId) public { require (!isContractPaused); require(token.ownerOf(animalId)==msg.sender); require(animalAgainstId[animalId].upForSale==true); animalAgainstId[animalId].upForSale=false; animalAgainstId[animalId].priceForSale=0; for (uint i=0;i<upForSaleList.length;i++) { if (upForSaleList[i]==animalId) delete upForSaleList[i]; } } function putMatingRequest(uint animalId, uint matePrice) public payable { require(!isContractPaused); require(!isMatingPaused); if (msg.sender!=owner) { require(msg.value>=priceForMateAdvertisement); } require(token.ownerOf(animalId)==msg.sender); animalAgainstId[animalId].upForMating=true; animalAgainstId[animalId].priceForMating=convertedpricetoEther; upForMatingList.push(animalId); } function putMatingRequest(uint animalId, uint matePrice) public payable { require(!isContractPaused); require(!isMatingPaused); if (msg.sender!=owner) { require(msg.value>=priceForMateAdvertisement); } require(token.ownerOf(animalId)==msg.sender); animalAgainstId[animalId].upForMating=true; animalAgainstId[animalId].priceForMating=convertedpricetoEther; upForMatingList.push(animalId); } uint convertedpricetoEther = matePrice; require(animalAgainstId[animalId].eggPhase==false); require(animalAgainstId[animalId].upForSale==false); require(animalAgainstId[animalId].upForMating==false); owner.transfer(msg.value); function withdrawMatingRequest(uint animalId) public { require(!isContractPaused); require(!isMatingPaused); require(token.ownerOf(animalId)==msg.sender); require(animalAgainstId[animalId].upForMating==true); animalAgainstId[animalId].upForMating=false; animalAgainstId[animalId].priceForMating=0; for (uint i=0;i<upForMatingList.length;i++) { if (upForMatingList[i]==animalId) delete upForMatingList[i]; } } function withdrawMatingRequest(uint animalId) public { require(!isContractPaused); require(!isMatingPaused); require(token.ownerOf(animalId)==msg.sender); require(animalAgainstId[animalId].upForMating==true); animalAgainstId[animalId].upForMating=false; animalAgainstId[animalId].priceForMating=0; for (uint i=0;i<upForMatingList.length;i++) { if (upForMatingList[i]==animalId) delete upForMatingList[i]; } } function validPurchase() internal constant returns (bool) { if(msg.value.div(weiPerAnimal)<1) return false; uint quotient=msg.value.div(weiPerAnimal); uint actualVal=quotient.mul(weiPerAnimal); if(msg.value>actualVal) return false; else return true; } function showMyAnimalBalance() public view returns (uint256 tokenBalance) { tokenBalance = token.balanceOf(msg.sender); } function setPriceRate(uint newPrice) public onlyOwner returns (bool) { uint convertedpricetoEther = newPrice; weiPerAnimal = convertedpricetoEther; } function setMateAdvertisementRate(uint256 newPrice) public onlyOwner returns (bool) { uint convertedpricetoEther = newPrice; priceForMateAdvertisement = convertedpricetoEther; } function setSaleAdvertisementRate(uint newPrice) public onlyOwner returns (bool) { uint convertedpricetoEther = newPrice; priceForSaleAdvertisement = convertedpricetoEther; } function setBuyingAssetsRate(uint newPrice) public onlyOwner returns (bool) { uint convertedpricetoEther = newPrice; priceForBuyingAssets = convertedpricetoEther; } function changeMaxMintable(uint limit) public onlyOwner { totalAnimalsMax = limit; } function getAllMatingAnimals() public constant returns (uint[]) { return upForMatingList; } function getAllSaleAnimals() public constant returns (uint[]) { return upForSaleList; } function changeFreeAnimalsLimit(uint limit) public onlyOwner { freeAnimalsLimit = limit; } function pauseMating(bool isPaused) public onlyOwner { isMatingPaused = isPaused; isMintingPaused = true; } function pauseContract(bool isPaused) public onlyOwner { isContractPaused = isPaused; } function pauseMinting(bool isPaused) public onlyOwner { isMintingPaused = isPaused; } function removeFromEggPhase(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<eggPhaseAnimalIds.length;j++) { if (eggPhaseAnimalIds[j]==animalId) { delete eggPhaseAnimalIds[j]; } } animalAgainstId[animalId].eggPhase = false; } } } function removeFromEggPhase(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<eggPhaseAnimalIds.length;j++) { if (eggPhaseAnimalIds[j]==animalId) { delete eggPhaseAnimalIds[j]; } } animalAgainstId[animalId].eggPhase = false; } } } function removeFromEggPhase(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<eggPhaseAnimalIds.length;j++) { if (eggPhaseAnimalIds[j]==animalId) { delete eggPhaseAnimalIds[j]; } } animalAgainstId[animalId].eggPhase = false; } } } function removeFromEggPhase(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<eggPhaseAnimalIds.length;j++) { if (eggPhaseAnimalIds[j]==animalId) { delete eggPhaseAnimalIds[j]; } } animalAgainstId[animalId].eggPhase = false; } } } function removeFromEggPhase(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<eggPhaseAnimalIds.length;j++) { if (eggPhaseAnimalIds[j]==animalId) { delete eggPhaseAnimalIds[j]; } } animalAgainstId[animalId].eggPhase = false; } } } function getChildrenAgainstAnimalId(uint id) public constant returns (uint[]) { return childrenIdAgainstAnimalId[id]; } function getEggPhaseList() public constant returns (uint[]) { return eggPhaseAnimalIds; } function getAnimalIdsWithPendingAssets() public constant returns (uint[]) { return animalIdsWithPendingAssetss; } function buyAssets(uint cId, uint aId) public payable { require(msg.value>=priceForBuyingAssets); require(!isContractPaused); require(token.ownerOf(aId)==msg.sender); require(animalAgainstId[aId].AssetsId==0); animalAgainstId[aId].AssetsId=cId; animalIdsWithPendingAssetss.push(aId); owner.transfer(msg.value); } function approvePendingAssets(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<animalIdsWithPendingAssetss.length;j++) { if (animalIdsWithPendingAssetss[j]==animalId) { delete animalIdsWithPendingAssetss[j]; } } } } } function approvePendingAssets(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<animalIdsWithPendingAssetss.length;j++) { if (animalIdsWithPendingAssetss[j]==animalId) { delete animalIdsWithPendingAssetss[j]; } } } } } function approvePendingAssets(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<animalIdsWithPendingAssetss.length;j++) { if (animalIdsWithPendingAssetss[j]==animalId) { delete animalIdsWithPendingAssetss[j]; } } } } } function approvePendingAssets(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<animalIdsWithPendingAssetss.length;j++) { if (animalIdsWithPendingAssetss[j]==animalId) { delete animalIdsWithPendingAssetss[j]; } } } } } function approvePendingAssets(uint animalId) public { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==msg.sender) { for (uint j=0;j<animalIdsWithPendingAssetss.length;j++) { if (animalIdsWithPendingAssetss[j]==animalId) { delete animalIdsWithPendingAssetss[j]; } } } } } function addMember(address member) public onlyOwner { memberAddresses.push(member); } function listMembers() public constant returns (address[]) { return memberAddresses; } function deleteMember(address member) public onlyOwner { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==member) { delete memberAddresses[i]; } } } function deleteMember(address member) public onlyOwner { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==member) { delete memberAddresses[i]; } } } function deleteMember(address member) public onlyOwner { for (uint i=0;i<memberAddresses.length;i++) { if (memberAddresses[i]==member) { delete memberAddresses[i]; } } } function updateAnimal(uint animalId, string name, string desc) public { require(msg.sender==token.ownerOf(animalId)); animalAgainstId[animalId].name=name; animalAgainstId[animalId].desc=desc; token.setAnimalMeta(animalId, name); } }
11,369,178
/** *Submitted for verification at Etherscan.io on 2022-03-26 */ /* guestlisted by @etherlect ____________________________________________________________ / \ /______________________________________________________________\ | [+] [+] [+] [+] [+] CLUB [+] [+] [+] [+] [+] | ================================================================ | [+] [+] [+] [+] [+] [+] [+] [+] [+] [+] [+] [+] | |----------------------------------------------------------- | | +-+ | +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ | +-+ | | |*| | |*| |*| |*| |*| |*| |*| |*| |*| |*| |*| | | | | | +-+ | +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ | +-+ | | [ ] | [+] [+] [+] [+] [+] [+] [+] [+] [+] [+] | [ ] | | +-+ | +--+ | +-+ | | | | | | | | | | | ============================================================== _ -- --_ -- _ - __ - | | __ -- - _ -- --- _ _ _ --- __ - _-- __ - | | _ - __ -- ___ -- _ - __ - __ -- - - _ - - | | _ - _ -- _ --- _ -- _ --- */ // File @openzeppelin/contracts/utils/introspection/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC721/[email protected] 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/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] 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/[email protected] 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/[email protected] 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/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/access/[email protected] 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() { _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); } } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File contracts/GuestlistedLibrary.sol pragma solidity ^0.8.12; library GuestlistedLibrary { struct Venue { string name; string location; uint[2][] indexes; string[] colors; uint[] djIndexes; } struct DJ { string firstName; string lastName; uint fontSize; } struct TokenData { uint tokenId; uint deterministicNumber; uint randomNumber; uint shapeRandomNumber; uint shapeIndex; string json; string date; string bg; string color; string shape; string attributes; string customMetadata; string djFullName; Venue venue; DJ dj; } function toString(uint value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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 + uint(value % 10))); value /= 10; } return string(buffer); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // File contracts/Guestlisted.sol pragma solidity ^0.8.12; pragma experimental ABIEncoderV2; contract Guestlisted is ERC721, ReentrancyGuard, Ownable { using ECDSA for bytes32; // ------------------------------------------------------------------------------------------------------- // // Mint config // // @startIndex => Start index from which to mint tokens // @endIndex => End index until which to mint tokens // @remaining => Remaining tokens to mint // @mintPrice => Current mint price (in WEI) // @maxTokensPerTransaction => Max allowed tokens to mint per transaction // @maxMintsPerWallet => Max allowed tokens to mint per wallet // @version => Used as a key along with wallet address in mintedPerWallet mapping // @isActive => State of the mint // @isRandom => Mint strategy (random / predictable) // @isOnlyForHolders => Allows only token holders to mint // @isOnWhitelist => Request a signature of wallet address by whitelistSigner // @whitelistSigner => Whitelist signer address which should be recovered while minting // // ------------------------------------------------------------------------------------------------------- struct MintConfig { uint startIndex; uint endIndex; uint remaining; uint mintPrice; uint maxTokensPerTransaction; uint maxMintsPerWallet; uint version; bool isActive; bool isRandom; bool isOnlyForHolders; bool isOnWhitelist; address whitelistSigner; } // ------------------------------------------------------------------------ // // If exists, custom metadata is added in the JSON metadata of tokens: // // { // ...other properties, // name: value, // name: value, // ... // } // // ------------------------------------------------------------------------ struct CustomMetadata { string name; string value; } // ------------------------------------------------------------------------ // // If exists, custom attributes are added in the JSON metadata of tokens: // // { // "attributes": { // ...other attributes, // { // "display_type": displayType, // "trait_type": traitType, // "value": value // } // } // } // // ------------------------------------------------------------------------ struct CustomAttribute { string displayType; string traitType; string value; } // ------------------------------------------------------------------------ // // Mapping storing the number of mints per wallet // string(abi.encodePacked(walletAddress, mintConfig.version)) => nbMinted // // ------------------------------------------------------------------------ mapping(string => uint) private mintedPerWallet; // -------------------------------------------------------- // // Mapping storing already minted tokens // // -------------------------------------------------------- mapping(uint => uint) private mintCache; // -------------------------------------------------------- // // Mappings for eventual future custom metadata & // attributes of tokens (added in the JSON if exists) // tokenId => CustomAttribute[] / CustomMetadata[] // // -------------------------------------------------------- mapping(uint => CustomAttribute[]) public customAttributes; mapping(uint => CustomMetadata[]) public customMetadata; // -------------------------------------------------------- // // Mapping returns if the color of the // text should be white given a bg color // bgColor (hex) => 0 (true) / 1 (false) // // -------------------------------------------------------- mapping(string => uint) public isTextColorWhite; // -------------------------------------------------------- // // Instantiation of global variables // // -------------------------------------------------------- uint public totalSupply; uint public minted; uint public burned; bool public isBurnActive; GuestlistedArtProxy public artProxyContract; MintConfig public mintConfig; GuestlistedLibrary.Venue[] private venues; GuestlistedLibrary.DJ[] private djs; // -------------------------------------------------------- // // Returns the metadata of a token (base64 encoded JSON) // // -------------------------------------------------------- function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token."); // -------------------------------------------------------- // // Get tokenData // // -------------------------------------------------------- GuestlistedLibrary.TokenData memory tokenData = getTokenData(_tokenId); // -------------------------------------------------------- // // Build attributes // // -------------------------------------------------------- tokenData.attributes = string( abi.encodePacked( '{"trait_type":"venue","value":"', tokenData.venue.name, '"}, {"trait_type":"dj","value":"', tokenData.djFullName, '"}, {"trait_type":"date","value":"', tokenData.date, '"}, {"trait_type":"shape","value":"', tokenData.shape, '"}, {"trait_type":"background","value":"', tokenData.bg, '"}, {"trait_type":"color","value":"', tokenData.color, '"}' ) ); // -------------------------------------------------------- // // Build custom attributes of the token if there is any // // -------------------------------------------------------- for (uint i = 0;i < customAttributes[_tokenId].length; i++) { tokenData.attributes = string( abi.encodePacked( tokenData.attributes, ',{"display_type":"', customAttributes[_tokenId][i].displayType, '","trait_type":"', customAttributes[_tokenId][i].traitType, '","value":"', customAttributes[_tokenId][i].value, '"}' ) ); } // -------------------------------------------------------- // // Build custom metadata of the token if there is any // // -------------------------------------------------------- for (uint i = 0;i < customMetadata[_tokenId].length; i++) { tokenData.customMetadata = string( abi.encodePacked( tokenData.customMetadata, ',"', customMetadata[_tokenId][i].name, '":"', customMetadata[_tokenId][i].value, '"' ) ); } // -------------------------------------------------------- // // Build final token metadata JSON // (get the image from proxy art contract) // // -------------------------------------------------------- tokenData.json = Base64.encode( bytes( abi.encodePacked( '{"name":"guestlisted #', GuestlistedLibrary.toString(_tokenId), ' - ', tokenData.djFullName, ' at ', tokenData.venue.name, '", "id": "', GuestlistedLibrary.toString(_tokenId), '", "description":"You are guestlisted.", "image":"', artProxyContract.draw(tokenData), '", "attributes":[', tokenData.attributes, ']', tokenData.customMetadata, '}' ) ) ); return string(abi.encodePacked("data:application/json;base64,", tokenData.json)); } // -------------------------------------------------------- // // Returns the data of a token (struct TokenData) // // -------------------------------------------------------- function getTokenData(uint256 _tokenId) private view returns (GuestlistedLibrary.TokenData memory) { // -------------------------------------------------------- // // Building tokenData used in the artProxyContract // // -------------------------------------------------------- GuestlistedLibrary.TokenData memory tokenData; tokenData.tokenId = _tokenId; tokenData.deterministicNumber = deterministic(GuestlistedLibrary.toString(_tokenId)); tokenData.randomNumber = random(GuestlistedLibrary.toString(_tokenId)); tokenData.shapeRandomNumber = tokenData.deterministicNumber % 100; // -------------------------------------------------------- // // Iterate indexes of each venue and pick the venue // corresponding to the _tokenId // // -------------------------------------------------------- for (uint i = 0; i < venues.length; i++) { for (uint j = 0; j < venues[i].indexes.length; j++) { if (venues[i].indexes[j][0] <= _tokenId && venues[i].indexes[j][1] >= _tokenId) { tokenData.venue = venues[i]; break; } } } // -------------------------------------------------------- // // Pick the date, bg, text color and dj for a given // tokenId and the selected venue // // -------------------------------------------------------- tokenData.date = getDate(_tokenId); tokenData.bg = tokenData.venue.colors[tokenData.deterministicNumber % tokenData.venue.colors.length]; tokenData.color = isTextColorWhite[tokenData.bg] == 1 ? 'ffffff' : '393D3F'; tokenData.dj = djs[tokenData.venue.djIndexes[tokenData.deterministicNumber % tokenData.venue.djIndexes.length]]; // -------------------------------------------------------- // // Pick a shape // // -------------------------------------------------------- // circle = 25% of chances tokenData.shapeIndex = 0; tokenData.shape = 'circle'; if (tokenData.shapeRandomNumber > 25 && tokenData.shapeRandomNumber <= 35) { // line => 10% of chances tokenData.shapeIndex = 4; tokenData.shape = 'line'; } else if (tokenData.shapeRandomNumber > 35 && tokenData.shapeRandomNumber <= 55) { // prism => 20% of chances tokenData.shapeIndex = 1; tokenData.shape = 'prism'; } else if (tokenData.shapeRandomNumber > 55 && tokenData.shapeRandomNumber <= 80) { // cube => 25% of chances tokenData.shapeIndex = 3; tokenData.shape = 'cube'; } else if (tokenData.shapeRandomNumber > 80 && tokenData.shapeRandomNumber <= 100) { // square => 20% of chances tokenData.shapeIndex = 2; tokenData.shape = 'square'; } tokenData.djFullName = string( abi.encodePacked( tokenData.dj.firstName, bytes(tokenData.dj.lastName).length == 0 ? '': string(abi.encodePacked(' ', tokenData.dj.lastName)) ) ); return tokenData; } // -------------------------------------------------------- // // Returns the image of a token (base64 encoded SVG) // // -------------------------------------------------------- function tokenImage(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "tokenImage query for nonexistent token."); return artProxyContract.draw(getTokenData(_tokenId)); } // -------------------------------------------------------- // // Returns a random index of token to mint depending on // sender addr and current block timestamp & difficulty // // -------------------------------------------------------- function getRandomTokenIndex (address senderAddress) internal returns (uint) { uint randomNumber = random(string(abi.encodePacked(senderAddress))); uint i = (randomNumber % mintConfig.remaining) + mintConfig.startIndex; // -------------------------------------------------------- // // If there's a cache at mintCache[i] then use it // otherwise use i itself // // -------------------------------------------------------- uint index = mintCache[i] == 0 ? i : mintCache[i]; // -------------------------------------------------------- // // Grab a number from the tail & decrease remaining // // -------------------------------------------------------- mintCache[i] = mintCache[mintConfig.remaining - 1 + mintConfig.startIndex] == 0 ? mintConfig.remaining - 1 + mintConfig.startIndex : mintCache[mintConfig.remaining - 1 + mintConfig.startIndex]; mintConfig.remaining--; return index; } function mint(uint _nbTokens, bytes memory signature) public payable nonReentrant { require(mintConfig.isActive, "The mint is not active at the moment."); require(_nbTokens > 0, "Number of tokens can not be less than or equal to 0."); require(_nbTokens <= mintConfig.maxTokensPerTransaction, "Number of tokens can not be higher than allowed."); require(mintConfig.remaining >= _nbTokens, "The mint would exceed the number of remaining tokens."); require(mintConfig.mintPrice * _nbTokens == msg.value, "Sent ETH value is incorrect."); // -------------------------------------------------------- // // Check signature if mintConfig.isOnWhitelist is true // // -------------------------------------------------------- if (mintConfig.isOnWhitelist) { address recoveredSigner = keccak256(abi.encodePacked(_msgSender())).toEthSignedMessageHash().recover(signature); require(recoveredSigner == mintConfig.whitelistSigner, "Your wallet is not whitelisted."); } // -------------------------------------------------------- // // Check if minter is holder if // mintConfig.isOnlyForHolders is true // // -------------------------------------------------------- if (mintConfig.isOnlyForHolders) { require(balanceOf(_msgSender()) > 0, "You have to own at least one token to mint more."); } // -------------------------------------------------------- // // Check if minter has not already reached the // limit of mints per wallet + update the mapping // minterKey is composed of the wallet address and version // version can be updated to reinit all wallets to 0 mints // // -------------------------------------------------------- string memory minterKey = string(abi.encodePacked(_msgSender(), mintConfig.version)); require(mintedPerWallet[minterKey] + _nbTokens <= mintConfig.maxMintsPerWallet, "Your wallet is not allowed to mint as many tokens."); mintedPerWallet[minterKey] += _nbTokens; // -------------------------------------------------------- // // Mint depending on mint strategy: random / predictable // // -------------------------------------------------------- if (mintConfig.isRandom) { for (uint i = 0; i < _nbTokens;i++) { totalSupply++; minted++; _safeMint(_msgSender(), getRandomTokenIndex(_msgSender())); } } else { for (uint i = 0; i < _nbTokens;i++) { // -------------------------------------------------------- // // Update mint cache & remaining before mint // // -------------------------------------------------------- totalSupply++; minted++; mintCache[minted] = mintConfig.remaining - 1 + mintConfig.startIndex; mintConfig.remaining--; _safeMint(_msgSender(), minted); } } } function burn(uint _tokenId) external { require(isBurnActive, "Burning disabled."); require(_exists(_tokenId), "The token does not exists."); require(ownerOf(_tokenId) == _msgSender(), "You are not the owner of the token."); totalSupply--; burned++; _burn(_tokenId); } // -------------------------------------------------------- // // Returns a date for a tokenId // date range: 01.01.22 - 28.12.25 // // -------------------------------------------------------- function getDate (uint256 _tokenId) internal pure returns (string memory) { uint deterministicNumber = deterministic(GuestlistedLibrary.toString(_tokenId)); uint day = deterministicNumber % 28 + 1; uint month = deterministicNumber % 12 + 1; uint yearDeterministic = deterministicNumber % 4; string memory yearString = '22'; if (yearDeterministic == 1) yearString = '23'; else if (yearDeterministic == 2) yearString = '24'; else if (yearDeterministic == 3) yearString = '25'; string memory dayString = GuestlistedLibrary.toString(day); if (day < 10) dayString = string(abi.encodePacked('0', dayString)); string memory monthString = GuestlistedLibrary.toString(month); if (month < 10) monthString = string(abi.encodePacked('0', monthString)); return string(abi.encodePacked(dayString, '.', monthString, '.', yearString)); } // -------------------------------------------------------- // // Returns a deterministic number for an input // // -------------------------------------------------------- function deterministic (string memory input) internal pure returns (uint) { return uint(keccak256(abi.encodePacked(input))); } // -------------------------------------------------------- // // Returns a relatively random number for an input // depending on current block timestamp & difficulty // // -------------------------------------------------------- function random (string memory input) internal view returns(uint) { return uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty, input))); } // -------------------------------------------------------- // // Updates a venue in the storage at specified index // Adds a new venue if the index is -1 // // -------------------------------------------------------- function updateVenue (int _index, GuestlistedLibrary.Venue memory _venue) public onlyOwner { require((_index == -1) || (uint(_index) < venues.length), 'Can not update non-existent venue.'); if (_index == -1) venues.push(_venue); else venues[uint(_index)] = _venue; } function getVenueByIndex (uint _index) external view returns (GuestlistedLibrary.Venue memory) { require(_index < venues.length , 'Venue does not exists.'); return venues[_index]; } // -------------------------------------------------------- // // Updates a dj in the storage at specified index // Adds a new dj if the index is -1 // // -------------------------------------------------------- function updateDJ (int _index, GuestlistedLibrary.DJ memory _dj) public onlyOwner { require((_index == -1) || (uint(_index) <= djs.length - 1), 'Can not update non-existent dj.'); if (_index == -1) djs.push(_dj); else djs[uint(_index)] = _dj; } function getDJByIndex (uint _index) external view returns (GuestlistedLibrary.DJ memory) { require(_index < djs.length , 'DJ does not exists.'); return djs[_index]; } function getMintedPerWallet (address minterAddress, uint version) external view returns (uint) { string memory minterKey = string(abi.encodePacked(minterAddress, version)); return mintedPerWallet[minterKey]; } function updateIsTextColorWhite (string memory bg, uint value) public onlyOwner { require(value == 0 || value == 1, 'Wrong value.'); isTextColorWhite[bg] = value; } function updateArtProxyContract(address _artProxyContractAddress) public onlyOwner { artProxyContract = GuestlistedArtProxy(_artProxyContractAddress); } // -------------------------------------------------------- // // Update the adress used to sign & recover whitelists // // -------------------------------------------------------- function updateWhitelistSigner(address _whitelistSigner) external onlyOwner { mintConfig.whitelistSigner = _whitelistSigner; } // ---------------------------------------------------------------- // // Erease and update the custom metadata for a set of tokens. // This metadata will be added to specified tokens in the // tokenURI method. // // ---------------------------------------------------------------- function updateCustomMetadata (uint[] memory _tokenIds, CustomMetadata[] memory _customMetadata) external onlyOwner { for (uint i = 0; i < _tokenIds.length; i++) { delete customMetadata[_tokenIds[i]]; for (uint j = 0; j < _customMetadata.length; j++) { customMetadata[_tokenIds[i]].push(_customMetadata[j]); } } } // ---------------------------------------------------------------- // // Erease and update the custom attributes for a set of tokens. // Those attributes will be added to specified tokens in the // tokenURI method. // // ---------------------------------------------------------------- function updateCustomAttributes (uint[] memory _tokenIds, CustomAttribute[] memory _customAttributes) external onlyOwner { for (uint i = 0; i < _tokenIds.length; i++) { delete customAttributes[_tokenIds[i]]; for (uint j = 0; j < _customAttributes.length; j++) { customAttributes[_tokenIds[i]].push(_customAttributes[j]); } } } function updateMintConfig(MintConfig memory _mintConfig) public onlyOwner { mintConfig = _mintConfig; } function flipBurnState() external onlyOwner { isBurnActive = !isBurnActive; } function flipMintState() external onlyOwner { mintConfig.isActive = !mintConfig.isActive; } function withdraw() external onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } // ---------------------------------------------------------------- // // Returns un array of tokens owned by an address // (gas optimisation of tokenOfOwnerByIndex from ERC721Enumerable) // // ---------------------------------------------------------------- function tokensOfOwner(address _ownerAddress) public virtual view returns (uint[] memory) { uint balance = balanceOf(_ownerAddress); uint[] memory tokens = new uint[](balance); uint tokenId; uint found; while (found < balance) { if (_exists(tokenId) && ownerOf(tokenId) == _ownerAddress) { tokens[found++] = tokenId; } tokenId++; } return tokens; } constructor( address _artProxyContractAddress, MintConfig memory _mintConfig, GuestlistedLibrary.Venue[] memory _venues, GuestlistedLibrary.DJ[] memory _djs, string[] memory bgsWithWhiteTextColor, uint[] memory _ownerReserve ) ERC721("guestlisted", "guestlist") Ownable() { // -------------------------------------------------------- // // Setup the art proxy contract instance // // -------------------------------------------------------- updateArtProxyContract(_artProxyContractAddress); // -------------------------------------------------------- // // Update the mintConfig // // -------------------------------------------------------- updateMintConfig(_mintConfig); // -------------------------------------------------------- // // Store venues // // -------------------------------------------------------- for (uint i = 0;i < _venues.length; i++) { updateVenue(-1, _venues[i]); } // -------------------------------------------------------- // // Store djs // // -------------------------------------------------------- for (uint i = 0;i < _djs.length; i++) { updateDJ(-1, _djs[i]); } // -------------------------------------------------------- // // Store backgounds that has white text color // // -------------------------------------------------------- for (uint i = 0; i < bgsWithWhiteTextColor.length; i++) { updateIsTextColorWhite(bgsWithWhiteTextColor[i], 1); } // -------------------------------------------------------- // // Mint owner reserved tokens // // -------------------------------------------------------- for (uint i = 0; i < _ownerReserve.length; i++) { mintCache[_ownerReserve[i]] = mintConfig.remaining - 1 + mintConfig.startIndex; totalSupply++; minted++; mintConfig.remaining--; _safeMint(owner(), _ownerReserve[i]); } } } // -------------------------------------------------------- // // Art proxy contract function signature // // -------------------------------------------------------- contract GuestlistedArtProxy { function draw (GuestlistedLibrary.TokenData memory tokenData) public view returns (string memory) {} }
-------------------------------------------------------- Returns a random index of token to mint depending on sender addr and current block timestamp & difficulty -------------------------------------------------------- -------------------------------------------------------- If there's a cache at mintCache[i] then use it otherwise use i itself -------------------------------------------------------- -------------------------------------------------------- Grab a number from the tail & decrease remaining --------------------------------------------------------
function getRandomTokenIndex (address senderAddress) internal returns (uint) { uint randomNumber = random(string(abi.encodePacked(senderAddress))); uint i = (randomNumber % mintConfig.remaining) + mintConfig.startIndex; uint index = mintCache[i] == 0 ? i : mintCache[i]; mintCache[i] = mintCache[mintConfig.remaining - 1 + mintConfig.startIndex] == 0 ? mintConfig.remaining - 1 + mintConfig.startIndex : mintCache[mintConfig.remaining - 1 + mintConfig.startIndex]; mintConfig.remaining--; return index; }
2,426,202
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; library Nibble { // keyToNibbles turns bytes into nibbles, assumes they are already ordered in LE function keyToNibbles(bytes memory src) internal pure returns (bytes memory des) { if (src.length == 0) { return des; } else if (src.length == 1 && uint8(src[0]) == 0) { return hex"0000"; } uint256 l = src.length * 2; des = new bytes(l); for (uint256 i = 0; i < src.length; i++) { des[2 * i] = bytes1(uint8(src[i]) / 16); des[2 * i + 1] = bytes1(uint8(src[i]) % 16); } } // nibblesToKeyLE turns a slice of nibbles w/ length k into a little endian byte array, assumes nibbles are already LE function nibblesToKeyLE(bytes memory src) internal pure returns (bytes memory des) { uint256 l = src.length; if (l % 2 == 0) { des = new bytes(l / 2); for (uint256 i = 0; i < l; i += 2) { uint8 a = uint8(src[i]); uint8 b = uint8(src[i + 1]); des[i / 2] = bytes1(((a << 4) & 0xF0) | (b & 0x0F)); } } else { des = new bytes(l / 2 + 1); des[0] = src[0]; for (uint256 i = 2; i < l; i += 2) { uint8 a = uint8(src[i - 1]); uint8 b = uint8(src[i]); des[i / 2] = bytes1(((a << 4) & 0xF0) | (b & 0x0F)); } } } }
nibblesToKeyLE turns a slice of nibbles w/ length k into a little endian byte array, assumes nibbles are already LE
function nibblesToKeyLE(bytes memory src) internal pure returns (bytes memory des) { uint256 l = src.length; if (l % 2 == 0) { des = new bytes(l / 2); for (uint256 i = 0; i < l; i += 2) { uint8 a = uint8(src[i]); uint8 b = uint8(src[i + 1]); des[i / 2] = bytes1(((a << 4) & 0xF0) | (b & 0x0F)); } des = new bytes(l / 2 + 1); des[0] = src[0]; for (uint256 i = 2; i < l; i += 2) { uint8 a = uint8(src[i - 1]); uint8 b = uint8(src[i]); des[i / 2] = bytes1(((a << 4) & 0xF0) | (b & 0x0F)); } } }
15,846,095
pragma solidity 0.4.25; // File: contracts/sogur/interfaces/IRedButton.sol /** * @title Red Button Interface. */ interface IRedButton { /** * @dev Get the state of the red-button. * @return The state of the red-button. */ function isEnabled() external view returns (bool); } // File: contracts/sogur/interfaces/IPaymentManager.sol /** * @title Payment Manager Interface. */ interface IPaymentManager { /** * @dev Retrieve the current number of outstanding payments. * @return The current number of outstanding payments. */ function getNumOfPayments() external view returns (uint256); /** * @dev Retrieve the sum of all outstanding payments. * @return The sum of all outstanding payments. */ function getPaymentsSum() external view returns (uint256); /** * @dev Compute differ payment. * @param _ethAmount The amount of ETH entitled by the client. * @param _ethBalance The amount of ETH retained by the payment handler. * @return The amount of differed ETH payment. */ function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256); /** * @dev Register a differed payment. * @param _wallet The payment wallet address. * @param _ethAmount The payment amount in ETH. */ function registerDifferPayment(address _wallet, uint256 _ethAmount) external; } // File: contracts/sogur/interfaces/IReserveManager.sol /** * @title Reserve Manager Interface. */ interface IReserveManager { /** * @dev Get a deposit-recommendation. * @param _balance The balance of the token-contract. * @return The address of the wallet permitted to deposit ETH into the token-contract. * @return The amount that should be deposited in order for the balance to reach `mid` ETH. */ function getDepositParams(uint256 _balance) external view returns (address, uint256); /** * @dev Get a withdraw-recommendation. * @param _balance The balance of the token-contract. * @return The address of the wallet permitted to withdraw ETH into the token-contract. * @return The amount that should be withdrawn in order for the balance to reach `mid` ETH. */ function getWithdrawParams(uint256 _balance) external view returns (address, uint256); } // File: contracts/sogur/interfaces/ISGRTokenManager.sol /** * @title SGR Token Manager Interface. */ interface ISGRTokenManager { /** * @dev Exchange ETH for SGR. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return The amount of SGR that the sender is entitled to. */ function exchangeEthForSgr(address _sender, uint256 _ethAmount) external returns (uint256); /** * @dev Handle after the ETH for SGR exchange operation. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @param _sgrAmount The amount of SGR given. */ function afterExchangeEthForSgr(address _sender, uint256 _ethAmount, uint256 _sgrAmount) external; /** * @dev Exchange SGR for ETH. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgrForEth(address _sender, uint256 _sgrAmount) external returns (uint256); /** * @dev Handle after the SGR for ETH exchange operation. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @param _ethAmount The amount of ETH given. * @return The is success result. */ function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool); /** * @dev Handle direct SGR transfer. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external; /** * @dev Handle after direct SGR transfer operation. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferResult The transfer result. * @return is success result. */ function afterTransfer(address _sender, address _to, uint256 _value, bool _transferResult) external returns (bool); /** * @dev Handle custodian SGR transfer. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external; /** * @dev Handle after custodian SGR transfer operation. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferFromResult The transferFrom result. * @return is success result. */ function afterTransferFrom(address _sender, address _from, address _to, uint256 _value, bool _transferFromResult) external returns (bool); /** * @dev Handle the operation of ETH deposit into the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract. * @param _amount The deposited ETH amount. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external returns (address, uint256); /** * @dev Handle the operation of ETH withdrawal from the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract prior the withdrawal. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function uponWithdraw(address _sender, uint256 _balance) external returns (address, uint256); /** * @dev Handle after ETH withdrawal from the SGRToken contract operation. * @param _sender The address of the account which has issued the operation. * @param _wallet The address of the withdrawal wallet. * @param _amount The ETH withdraw amount. * @param _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. * @param _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. */ function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external; /** * @dev Upon SGR mint for SGN holders. * @param _value The amount of SGR to mint. */ function uponMintSgrForSgnHolders(uint256 _value) external; /** * @dev Handle after SGR mint for SGN holders. * @param _value The minted amount of SGR. */ function afterMintSgrForSgnHolders(uint256 _value) external; /** * @dev Upon SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function uponTransferSgrToSgnHolder(address _to, uint256 _value) external; /** * @dev Handle after SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The transferred amount of SGR. */ function afterTransferSgrToSgnHolder(address _to, uint256 _value) external; /** * @dev Upon ETH transfer to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgrHolder(address _to, uint256 _value, bool _status) external; /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function getDepositParams() external view returns (address, uint256); /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function getWithdrawParams() external view returns (address, uint256); } // File: contracts/sogur/interfaces/ITransactionManager.sol /** * @title Transaction Manager Interface. */ interface ITransactionManager { /** * @dev Buy SGR in exchange for ETH. * @param _ethAmount The amount of ETH received from the buyer. * @return The amount of SGR that the buyer is entitled to receive. */ function buy(uint256 _ethAmount) external returns (uint256); /** * @dev Sell SGR in exchange for ETH. * @param _sgrAmount The amount of SGR received from the seller. * @return The amount of ETH that the seller is entitled to receive. */ function sell(uint256 _sgrAmount) external returns (uint256); } // File: contracts/sogur/interfaces/ISGRAuthorizationManager.sol /** * @title SGR Authorization Manager Interface. */ interface ISGRAuthorizationManager { /** * @dev Determine whether or not a user is authorized to buy SGR. * @param _sender The address of the user. * @return Authorization status. */ function isAuthorizedToBuy(address _sender) external view returns (bool); /** * @dev Determine whether or not a user is authorized to sell SGR. * @param _sender The address of the user. * @return Authorization status. */ function isAuthorizedToSell(address _sender) external view returns (bool); /** * @dev Determine whether or not a user is authorized to transfer SGR to another user. * @param _sender The address of the source user. * @param _target The address of the target user. * @return Authorization status. */ function isAuthorizedToTransfer(address _sender, address _target) external view returns (bool); /** * @dev Determine whether or not a user is authorized to transfer SGR from one user to another user. * @param _sender The address of the custodian user. * @param _source The address of the source user. * @param _target The address of the target user. * @return Authorization status. */ function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool); /** * @dev Determine whether or not a user is authorized for public operation. * @param _sender The address of the user. * @return Authorization status. */ function isAuthorizedForPublicOperation(address _sender) external view returns (bool); } // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ; bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager"; bytes32 internal constant _ISGRToken_ = "ISGRToken" ; bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ; bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ; bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ; bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: contracts/wallet_trading_limiter/interfaces/IWalletsTradingLimiter.sol /** * @title Wallets Trading Limiter Interface. */ interface IWalletsTradingLimiter { /** * @dev Increment the limiter value of a wallet. * @param _wallet The address of the wallet. * @param _value The amount to be updated. */ function updateWallet(address _wallet, uint256 _value) external; } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/sogur/SGRTokenManager.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title SGR Token Manager. */ contract SGRTokenManager is ISGRTokenManager, ContractAddressLocatorHolder { string public constant VERSION = "2.0.0"; using SafeMath for uint256; event ExchangeEthForSgrCompleted(address indexed _user, uint256 _input, uint256 _output); event ExchangeSgrForEthCompleted(address indexed _user, uint256 _input, uint256 _output); event MintSgrForSgnHoldersCompleted(uint256 _value); event TransferSgrToSgnHolderCompleted(address indexed _to, uint256 _value); event TransferEthToSgrHolderCompleted(address indexed _to, uint256 _value, bool _status); event DepositCompleted(address indexed _sender, uint256 _balance, uint256 _amount); event WithdrawCompleted(address indexed _sender, uint256 _balance, uint256 _amount); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the ISGRAuthorizationManager interface. */ function getSGRAuthorizationManager() public view returns (ISGRAuthorizationManager) { return ISGRAuthorizationManager(getContractAddress(_ISGRAuthorizationManager_)); } /** * @dev Return the contract which implements the ITransactionManager interface. */ function getTransactionManager() public view returns (ITransactionManager) { return ITransactionManager(getContractAddress(_ITransactionManager_)); } /** * @dev Return the contract which implements the IWalletsTradingLimiter interface. */ function getSellWalletsTradingLimiter() public view returns (IWalletsTradingLimiter) { return IWalletsTradingLimiter(getContractAddress(_SellWalletsTradingLimiter_SGRTokenManager_)); } /** * @dev Return the contract which implements the IWalletsTradingLimiter interface. */ function getBuyWalletsTradingLimiter() public view returns (IWalletsTradingLimiter) { return IWalletsTradingLimiter(getContractAddress(_BuyWalletsTradingLimiter_SGRTokenManager_)); } /** * @dev Return the contract which implements the IReserveManager interface. */ function getReserveManager() public view returns (IReserveManager) { return IReserveManager(getContractAddress(_IReserveManager_)); } /** * @dev Return the contract which implements the IPaymentManager interface. */ function getPaymentManager() public view returns (IPaymentManager) { return IPaymentManager(getContractAddress(_IPaymentManager_)); } /** * @dev Return the contract which implements the IRedButton interface. */ function getRedButton() public view returns (IRedButton) { return IRedButton(getContractAddress(_IRedButton_)); } /** * @dev Reverts if called when the red button is enabled. */ modifier onlyIfRedButtonIsNotEnabled() { require(!getRedButton().isEnabled(), "red button is enabled"); _; } /** * @dev Exchange ETH for SGR. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return The amount of SGR that the sender is entitled to. */ function exchangeEthForSgr(address _sender, uint256 _ethAmount) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled returns (uint256) { require(getSGRAuthorizationManager().isAuthorizedToBuy(_sender), "exchanging ETH for SGR is not authorized"); uint256 sgrAmount = getTransactionManager().buy(_ethAmount); emit ExchangeEthForSgrCompleted(_sender, _ethAmount, sgrAmount); getBuyWalletsTradingLimiter().updateWallet(_sender, sgrAmount); return sgrAmount; } /** * @dev Handle after the ETH for SGR exchange operation. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @param _sgrAmount The amount of SGR given. */ function afterExchangeEthForSgr(address _sender, uint256 _ethAmount, uint256 _sgrAmount) external { _sender; _ethAmount; _sgrAmount; } /** * @dev Exchange SGR for ETH. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgrForEth(address _sender, uint256 _sgrAmount) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled returns (uint256) { require(getSGRAuthorizationManager().isAuthorizedToSell(_sender), "exchanging SGR for ETH is not authorized"); uint256 ethAmount = getTransactionManager().sell(_sgrAmount); emit ExchangeSgrForEthCompleted(_sender, _sgrAmount, ethAmount); getSellWalletsTradingLimiter().updateWallet(_sender, _sgrAmount); IPaymentManager paymentManager = getPaymentManager(); uint256 paymentETHAmount = paymentManager.computeDifferPayment(ethAmount, msg.sender.balance); if (paymentETHAmount > 0) paymentManager.registerDifferPayment(_sender, paymentETHAmount); assert(ethAmount >= paymentETHAmount); return ethAmount - paymentETHAmount; } /** * @dev Handle after the SGR for ETH exchange operation. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @param _ethAmount The amount of ETH given. * @return The is success result. */ function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool) { _sender; _sgrAmount; _ethAmount; return true; } /** * @dev Handle direct SGR transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external only(_ISGRToken_) { _sender; _to; _value; } /** * @dev Handle after direct SGR transfer operation. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferResult The transfer result. * @return is success result. */ function afterTransfer(address _sender, address _to, uint256 _value, bool _transferResult) external returns (bool) { _sender; _to; _value; return _transferResult; } /** * @dev Handle custodian SGR transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external only(_ISGRToken_) { _sender; _from; _to; _value; } /** * @dev Handle after custodian SGR transfer operation. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferFromResult The transferFrom result. * @return is success result. */ function afterTransferFrom(address _sender, address _from, address _to, uint256 _value, bool _transferFromResult) external returns (bool) { _sender; _from; _to; _value; return _transferFromResult; } /** * @dev Handle the operation of ETH deposit into the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract. * @param _amount The deposited ETH amount. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external only(_ISGRToken_) returns (address, uint256) { uint256 ethBalancePriorToDeposit = _balance.sub(_amount); (address wallet, uint256 recommendationAmount) = getReserveManager().getDepositParams(ethBalancePriorToDeposit); require(wallet == _sender, "caller is illegal"); require(recommendationAmount > 0, "operation is not required"); emit DepositCompleted(_sender, ethBalancePriorToDeposit, _amount); return (wallet, recommendationAmount); } /** * @dev Handle the operation of ETH withdrawal from the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract prior the withdrawal. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function uponWithdraw(address _sender, uint256 _balance) external only(_ISGRToken_) returns (address, uint256) { require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(_sender), "withdraw is not authorized"); (address wallet, uint256 amount) = getReserveManager().getWithdrawParams(_balance); require(wallet != address(0), "caller is illegal"); require(amount > 0, "operation is not required"); emit WithdrawCompleted(_sender, _balance, amount); return (wallet, amount); } /** * @dev Handle after ETH withdrawal from the SGRToken contract operation. * @param _sender The address of the account which has issued the operation. * @param _wallet The address of the withdrawal wallet. * @param _amount The ETH withdraw amount. * @param _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. * @param _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. */ function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external { _sender; _wallet; _amount; _priorWithdrawEthBalance; _afterWithdrawEthBalance; } /** * @dev Upon SGR mint for SGN holders. * @param _value The amount of SGR to mint. */ function uponMintSgrForSgnHolders(uint256 _value) external only(_ISGRToken_) { emit MintSgrForSgnHoldersCompleted(_value); } /** * @dev Handle after SGR mint for SGN holders. * @param _value The minted amount of SGR. */ function afterMintSgrForSgnHolders(uint256 _value) external { _value; } /** * @dev Upon SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function uponTransferSgrToSgnHolder(address _to, uint256 _value) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled { emit TransferSgrToSgnHolderCompleted(_to, _value); } /** * @dev Handle after SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The transferred amount of SGR. */ function afterTransferSgrToSgnHolder(address _to, uint256 _value) external { _to; _value; } /** * @dev Upon ETH transfer to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgrHolder(address _to, uint256 _value, bool _status) external only(_ISGRToken_) { emit TransferEthToSgrHolderCompleted(_to, _value, _status); } /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function getDepositParams() external view only(_ISGRToken_) returns (address, uint256) { return getReserveManager().getDepositParams(msg.sender.balance); } /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function getWithdrawParams() external view only(_ISGRToken_) returns (address, uint256) { return getReserveManager().getWithdrawParams(msg.sender.balance); } }
Handle the operation of ETH deposit into the SGRToken contract. _sender The address of the account which has issued the operation. _balance The amount of ETH in the SGRToken contract. _amount The deposited ETH amount. return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract./
function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external only(_ISGRToken_) returns (address, uint256) { uint256 ethBalancePriorToDeposit = _balance.sub(_amount); (address wallet, uint256 recommendationAmount) = getReserveManager().getDepositParams(ethBalancePriorToDeposit); require(wallet == _sender, "caller is illegal"); require(recommendationAmount > 0, "operation is not required"); emit DepositCompleted(_sender, ethBalancePriorToDeposit, _amount); return (wallet, recommendationAmount); }
7,635,324
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; interface IERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address spender, address recipient, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external; } contract ERC20 is IERC20 { string public symbol; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; constructor(string memory _symbol, uint256 supply) { symbol = _symbol; balanceOf[msg.sender] = supply; } function transfer(address addr, uint256 amount) public override returns (bool) { return transferFrom(msg.sender, addr, amount); } function transferFrom( address spender, address addr, uint256 amount ) public override returns (bool) { require(balanceOf[spender] >= amount, "Not enough balance"); balanceOf[spender] -= amount; balanceOf[addr] += amount; return true; } function approve(address spender, uint256 amount) public pure override returns (bool) { spender; amount; return false; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override { // assuming signature is correct allowance[owner][spender] = value; deadline; v; r; s; } function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) public override { validAfter; validBefore; nonce; v; r; s; // assuming signature is correct transferFrom(from, to, value); } }
assuming signature is correct
function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) public override { validAfter; validBefore; nonce; v; r; s; transferFrom(from, to, value); }
1,761,156
pragma solidity ^0.5.16; import "./BToken.sol"; import "./PriceOracle.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./BAIControllerStorage.sol"; import "./BAIUnitroller.sol"; import "./BAI/BAI.sol"; interface ComptrollerLensInterface { function protocolPaused() external view returns (bool); function mintedBAIs(address account) external view returns (uint); function vaiMintRate() external view returns (uint); function venusBAIRate() external view returns (uint); function venusAccrued(address account) external view returns(uint); function getAssetsIn(address account) external view returns (BToken[] memory); function oracle() external view returns (PriceOracle); function distributeBAIMinterBai(address vaiMinter, bool distributeAll) external; } /** * @title Bai's BAI Comptroller Contract * @author Bai */ contract BAIController is BAIControllerStorage, BAIControllerErrorReporter, Exponential { /// @notice Emitted when Comptroller is changed event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when BAI is minted */ event MintBAI(address minter, uint mintBAIAmount); /** * @notice Event emitted when BAI is repaid */ event RepayBAI(address repayer, uint repayBAIAmount); /// @notice The initial Bai index for a market uint224 public constant venusInitialIndex = 1e36; /*** Main Actions ***/ function mintBAI(uint mintBAIAmount) external returns (uint) { if(address(comptroller) != address(0)) { require(!ComptrollerLensInterface(address(comptroller)).protocolPaused(), "protocol is paused"); address minter = msg.sender; // Keep the flywheel moving updateBaiBAIMintIndex(); ComptrollerLensInterface(address(comptroller)).distributeBAIMinterBai(minter, false); uint oErr; MathError mErr; uint accountMintBAINew; uint accountMintableBAI; (oErr, accountMintableBAI) = getMintableBAI(minter); if (oErr != uint(Error.NO_ERROR)) { return uint(Error.REJECTION); } // check that user have sufficient mintableBAI balance if (mintBAIAmount > accountMintableBAI) { return fail(Error.REJECTION, FailureInfo.BAI_MINT_REJECTION); } (mErr, accountMintBAINew) = addUInt(ComptrollerLensInterface(address(comptroller)).mintedBAIs(minter), mintBAIAmount); require(mErr == MathError.NO_ERROR, "BAI_MINT_AMOUNT_CALCULATION_FAILED"); uint error = comptroller.setMintedBAIOf(minter, accountMintBAINew); if (error != 0 ) { return error; } BAI(getBAIAddress()).mint(minter, mintBAIAmount); emit MintBAI(minter, mintBAIAmount); return uint(Error.NO_ERROR); } } /** * @notice Repay BAI */ function repayBAI(uint repayBAIAmount) external returns (uint) { if(address(comptroller) != address(0)) { require(!ComptrollerLensInterface(address(comptroller)).protocolPaused(), "protocol is paused"); address repayer = msg.sender; updateBaiBAIMintIndex(); ComptrollerLensInterface(address(comptroller)).distributeBAIMinterBai(repayer, false); uint actualBurnAmount; uint vaiBalance = ComptrollerLensInterface(address(comptroller)).mintedBAIs(repayer); if(vaiBalance > repayBAIAmount) { actualBurnAmount = repayBAIAmount; } else { actualBurnAmount = vaiBalance; } uint error = comptroller.setMintedBAIOf(repayer, vaiBalance - actualBurnAmount); if (error != 0) { return error; } BAI(getBAIAddress()).burn(repayer, actualBurnAmount); emit RepayBAI(repayer, actualBurnAmount); return uint(Error.NO_ERROR); } } /** * @notice Initialize the BaiBAIState */ function _initializeBaiBAIState(uint blockNumber) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } if (isBaiBAIInitialized == false) { isBaiBAIInitialized = true; uint vaiBlockNumber = blockNumber == 0 ? getBlockNumber() : blockNumber; venusBAIState = BaiBAIState({ index: venusInitialIndex, block: safe32(vaiBlockNumber, "block number overflows") }); } } /** * @notice Accrue XBID to by updating the BAI minter index */ function updateBaiBAIMintIndex() public returns (uint) { uint vaiMinterSpeed = ComptrollerLensInterface(address(comptroller)).venusBAIRate(); uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(venusBAIState.block)); if (deltaBlocks > 0 && vaiMinterSpeed > 0) { uint vaiAmount = BAI(getBAIAddress()).totalSupply(); uint venusAccrued = mul_(deltaBlocks, vaiMinterSpeed); Double memory ratio = vaiAmount > 0 ? fraction(venusAccrued, vaiAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: venusBAIState.index}), ratio); venusBAIState = BaiBAIState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { venusBAIState.block = safe32(blockNumber, "block number overflows"); } } /** * @notice Calculate XBID accrued by a BAI minter * @param vaiMinter The address of the BAI minter to distribute XBID to */ function calcDistributeBAIMinterBai(address vaiMinter) public returns(uint, uint, uint, uint) { // Check caller is comptroller if (msg.sender != address(comptroller)) { return (fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK), 0, 0, 0); } Double memory vaiMintIndex = Double({mantissa: venusBAIState.index}); Double memory vaiMinterIndex = Double({mantissa: venusBAIMinterIndex[vaiMinter]}); venusBAIMinterIndex[vaiMinter] = vaiMintIndex.mantissa; if (vaiMinterIndex.mantissa == 0 && vaiMintIndex.mantissa > 0) { vaiMinterIndex.mantissa = venusInitialIndex; } Double memory deltaIndex = sub_(vaiMintIndex, vaiMinterIndex); uint vaiMinterAmount = ComptrollerLensInterface(address(comptroller)).mintedBAIs(vaiMinter); uint vaiMinterDelta = mul_(vaiMinterAmount, deltaIndex); uint vaiMinterAccrued = add_(ComptrollerLensInterface(address(comptroller)).venusAccrued(vaiMinter), vaiMinterDelta); return (uint(Error.NO_ERROR), vaiMinterAccrued, vaiMinterDelta, vaiMintIndex.mantissa); } /*** Admin Functions ***/ /** * @notice Sets a new comptroller * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface comptroller_) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; comptroller = comptroller_; emit NewComptroller(oldComptroller, comptroller_); return uint(Error.NO_ERROR); } function _become(BAIUnitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @dev Local vars for avoiding stack-depth limits in calculating account total supply balance. * Note that `bTokenBalance` is the number of bTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountAmountLocalVars { uint totalSupplyAmount; uint sumSupply; uint sumBorrowPlusEffects; uint bTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } function getMintableBAI(address minter) public view returns (uint, uint) { PriceOracle oracle = ComptrollerLensInterface(address(comptroller)).oracle(); BToken[] memory enteredMarkets = ComptrollerLensInterface(address(comptroller)).getAssetsIn(minter); AccountAmountLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; uint accountMintableBAI; uint i; /** * We use this formula to calculate mintable BAI amount. * totalSupplyAmount * BAIMintRate - (totalBorrowAmount + mintedBAIOf) */ for (i = 0; i < enteredMarkets.length; i++) { (oErr, vars.bTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = enteredMarkets[i].getAccountSnapshot(minter); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (uint(Error.SNAPSHOT_ERROR), 0); } vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(enteredMarkets[i]); if (vars.oraclePriceMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); (mErr, vars.tokensToDenom) = mulExp(vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } // sumSupply += tokensToDenom * bTokenBalance (mErr, vars.sumSupply) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.bTokenBalance, vars.sumSupply); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } } (mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, ComptrollerLensInterface(address(comptroller)).mintedBAIs(minter)); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mErr, accountMintableBAI) = mulUInt(vars.sumSupply, ComptrollerLensInterface(address(comptroller)).vaiMintRate()); require(mErr == MathError.NO_ERROR, "BAI_MINT_AMOUNT_CALCULATION_FAILED"); (mErr, accountMintableBAI) = divUInt(accountMintableBAI, 10000); require(mErr == MathError.NO_ERROR, "BAI_MINT_AMOUNT_CALCULATION_FAILED"); (mErr, accountMintableBAI) = subUInt(accountMintableBAI, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (uint(Error.REJECTION), 0); } return (uint(Error.NO_ERROR), accountMintableBAI); } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the BAI token * @return The address of BAI */ function getBAIAddress() public view returns (address) { return 0x4BD17003473389A42DAF6a0a729f6Fdb328BbBd7; } }
Emitted when Comptroller is changed Event emitted when BAI is minted/ Event emitted when BAI is repaid/ The initial Bai index for a market Main Actions / Keep the flywheel moving check that user have sufficient mintableBAI balance
function mintBAI(uint mintBAIAmount) external returns (uint) { if(address(comptroller) != address(0)) { require(!ComptrollerLensInterface(address(comptroller)).protocolPaused(), "protocol is paused"); address minter = msg.sender; updateBaiBAIMintIndex(); ComptrollerLensInterface(address(comptroller)).distributeBAIMinterBai(minter, false); uint oErr; MathError mErr; uint accountMintBAINew; uint accountMintableBAI; (oErr, accountMintableBAI) = getMintableBAI(minter); if (oErr != uint(Error.NO_ERROR)) { return uint(Error.REJECTION); } if (mintBAIAmount > accountMintableBAI) { return fail(Error.REJECTION, FailureInfo.BAI_MINT_REJECTION); } (mErr, accountMintBAINew) = addUInt(ComptrollerLensInterface(address(comptroller)).mintedBAIs(minter), mintBAIAmount); require(mErr == MathError.NO_ERROR, "BAI_MINT_AMOUNT_CALCULATION_FAILED"); uint error = comptroller.setMintedBAIOf(minter, accountMintBAINew); if (error != 0 ) { return error; } BAI(getBAIAddress()).mint(minter, mintBAIAmount); emit MintBAI(minter, mintBAIAmount); return uint(Error.NO_ERROR); } }
13,129,208
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// _ _ _ _ _ _ /// | |_ ___ ___| |_|_|___ ___| | | |_ ___ ___ ___ ___ ___ _____ ___ |_|___ /// | _| .'| _| _| | _| .'| | | _| .'| | . | _| .'| |_ -| _ | | . | /// |_| |__,|___|_| |_|___|__,|_| |_| |__,|_|_|_ |_| |__,|_|_|_|___| |_| |_|___| /// |___| /// /// tacticaltangrams.io /// _ _ /// |_|_____ ___ ___ ___| |_ ___ /// | | | . | . | _| _|_ -| /// |_|_|_|_| _|___|_| |_| |___| /// |_| import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./State.sol"; import "./Team.sol"; import "./VRFD20.sol"; /// _ _ ___ /// |_|___| |_ ___ ___| _|___ ___ ___ ___ /// | | | _| -_| _| _| .'| _| -_|_ -| /// |_|_|_|_| |___|_| |_| |__,|___|___|___| interface TangramContract { function getGeneration(uint tokenId) external pure returns (uint); function getTanMetadata(uint tokenId, uint generation, uint generationSeed) external pure returns (string memory); } /// _ _ _____ /// ___ ___ ___| |_ ___ ___ ___| |_ |_ _|___ ___ /// | _| . | | _| _| .'| _| _| | | | .'| | /// |___|___|_|_|_| |_| |__,|___|_| |_| |__,|_|_| /// @title Tactical Tangrams main Tan contract /// @author tacticaltangrams.io /// @notice Tracks all Tan operations for tacticaltangrams.io. This makes this contract the OpenSea Tan collection contract Tan is ERC721Enumerable, Ownable, Pausable, State, Team, VRFD20 { /// @notice Emit Generation closing event; triggered by swapping 80+ Tans for the current generation /// @param generation Generation that is closing event GenerationClosing(uint generation); /// @notice Emit Generation closed event /// @param generation Generation that is closed event GenerationClosed(uint generation); /// _ _ /// ___ ___ ___ ___| |_ ___ _ _ ___| |_ ___ ___ /// | _| . | |_ -| _| _| | | _| _| . | _| /// |___|___|_|_|___|_| |_| |___|___|_| |___|_| /// @notice Deployment constructor /// @param _name ERC721 name of token /// @param _symbol ERC721 symbol of token /// @param _openPremintAtDeployment Opens premint directly at contract deployment /// @param _vrfCoordinator Chainlink VRF Coordinator address /// @param _link LINK token address /// @param _keyHash Public key against which randomness is created /// @param _fee VRF Chainlink fee in LINK /// @param _teamAddresses List of team member's addresses; first address is emergency address /// @param _tangramContract Address for Tangram contract constructor( address payable[TEAM_SIZE] memory _teamAddresses, string memory _name, string memory _symbol, bool _openPremintAtDeployment, address _vrfCoordinator, address _link, bytes32 _keyHash, uint _fee, address _tangramContract ) ERC721( _name, _symbol ) Team( _teamAddresses ) VRFD20( _vrfCoordinator, _link, _keyHash, _fee ) { vrfCoordinator = _vrfCoordinator; setTangramContract(_tangramContract); if (_openPremintAtDeployment) { changeState( StateType.DEPLOYED, StateType.PREMINT); } } /// _ _ /// _____|_|___| |_ /// | | | | _| /// |_|_|_|_|_|_|_| uint constant public MAX_MINT = 15554; uint constant public MAX_TANS_OG = 7; uint constant public MAX_TANS_WL = 7; uint constant public MAX_TANS_PUBLIC = 14; uint constant public PRICE_WL = 2 * 1e16; uint constant public PRICE_PUBLIC = 3 * 1e16; bytes32 private merkleRootOG = 0x67a345396a56431c46add239308b6fcfbab7dbf09287447d3f5f2458c0cccdc5; bytes32 private merkleRootWL = 0xf6c54efaf65ac33f79611e973313be91913aaf019de02d6d3ae1e6566f75929a; mapping (address => bool) private addressPreminted; mapping (uint => uint) public mintCounter; string private constant INVALID_NUMBER_OF_TANS = "Invalid number of tans or no more tans left"; /// @notice Get maximum number of mints for the given generation /// @param generation Generation to get max mints for /// @return Maximum number of mints for generation function maxMintForGeneration(uint generation) public pure generationBetween(generation, 1, 7) returns (uint) { if (generation == 7) { return 55; } if (generation == 6) { return 385; } if (generation == 5) { return 980; } if (generation == 4) { return 2310; } if (generation == 3) { return 5005; } if (generation == 2) { return 9156; } return MAX_MINT; } /// @notice Get number of mints for the given generation for closing announcement /// @param generation Generation to get max mints for /// @return Maximum number of mints for generation function maxMintForGenerationBeforeClosing(uint generation) public pure generationBetween(generation, 2, 6) returns (uint) { if (generation == 6) { return 308; } if (generation == 5) { return 784; } if (generation == 4) { return 1848; } if (generation == 3) { return 4004; } return 7325; } /// @notice Get the lowest Tan ID for a given generation /// @param generation Generation to get lowest ID for /// @return Lowest Tan ID for generation function mintStartNumberForGeneration(uint generation) public pure generationBetween(generation, 1, 7) returns (uint) { uint tmp = 1; for (uint gen = 1; gen <= 7; gen++) { if (generation == gen) { return tmp; } tmp += maxMintForGeneration(gen); } return 0; } /// @notice Public mint method. Checks whether the paid price is correct and max. 14 Tans are minted per tx /// @param numTans number of Tans to mint function mint(uint numTans) external payable forPrice(numTans, PRICE_PUBLIC, msg.value) inState(StateType.MINT) limitTans(numTans, MAX_TANS_PUBLIC) { mintLocal(numTans); } /// @notice Mint helper method /// @dev All checks need to be performed before calling this method /// @param numTans number of Tans to mint function mintLocal(uint numTans) private inEitherState(StateType.PREMINT, StateType.MINT) whenNotPaused() { for (uint mintedTan = 0; mintedTan < numTans; mintedTan++) { _mint(_msgSender(), totalSupply() + 1); } } /// @notice Mint next-gen Tans at Tangram swap /// @param numTans number of Tans to mint /// @param _for Address to mint Tans for function mintForNextGeneration(uint numTans, address _for) external generationBetween(currentGeneration, 1, 6) inStateOrAbove(StateType.GENERATIONSTARTED) onlyTangramContract() whenNotPaused() { uint nextGeneration = currentGeneration + 1; uint maxMintForNextGeneration = maxMintForGeneration(nextGeneration); require( mintCounter[nextGeneration] + numTans <= maxMintForNextGeneration, INVALID_NUMBER_OF_TANS ); for (uint mintedTan = 0; mintedTan < numTans; mintedTan++) { _mint( _for, mintStartNumberForGeneration(nextGeneration) + mintCounter[nextGeneration]++ ); } } /// @notice OG mint method. Allowed once per OG minter, OG proof is by merkle proof. Max 7 Tans allowed /// @dev Method is not payable since OG mint for free /// @param merkleProof Merkle proof of minter address for OG tree /// @param numTans Number of Tans to mint function mintOG(bytes32[] calldata merkleProof, uint numTans) external inEitherState(StateType.PREMINT, StateType.MINT) isValidMerkleProof(merkleRootOG, merkleProof) limitTans(numTans, MAX_TANS_OG) oneMint() { addressPreminted[_msgSender()] = true; mintLocal(numTans); } /// @notice WL mint method. Allowed once per WL minter, WL proof is by merkle proof. Max 7 Tans allowed /// @param merkleProof Merkle proof of minter address for WL tree /// @param numTans Number of Tans to mint function mintWL(bytes32[] calldata merkleProof, uint numTans) external payable forPrice(numTans, PRICE_WL, msg.value) inEitherState(StateType.PREMINT, StateType.MINT) isValidMerkleProof(merkleRootWL, merkleProof) limitTans(numTans, MAX_TANS_WL) oneMint() { addressPreminted[_msgSender()] = true; mintLocal(numTans); } /// @notice Update merkle roots for OG/WL minters /// @param og OG merkle root /// @param wl WL merkle root function setMerkleRoot(bytes32 og, bytes32 wl) external onlyOwner() { merkleRootOG = og; merkleRootWL = wl; } /// @notice Require correct paid price /// @dev WL and public mint pay a fixed price per Tan /// @param numTans Number of Tans to mint /// @param unitPrice Fixed price per Tan /// @param ethSent Value of ETH sent in this transaction modifier forPrice(uint numTans, uint unitPrice, uint ethSent) { require( numTans * unitPrice == ethSent, "Wrong value sent" ); _; } /// @notice Verify provided merkle proof to given root /// @dev Root is manually generated before contract deployment. Proof is automatically provided by minting site based on connected wallet address. /// @param root Merkle root to verify against /// @param proof Merkle proof to verify modifier isValidMerkleProof(bytes32 root, bytes32[] calldata proof) { require( MerkleProof.verify(proof, root, keccak256(abi.encodePacked(_msgSender()))), "Invalid proof" ); _; } /// @notice Require a valid number of Tans /// @param numTans Number of Tans to mint /// @param maxTans Maximum number of Tans to allow modifier limitTans(uint numTans, uint maxTans) { require( numTans >= 1 && numTans <= maxTans && totalSupply() + numTans <= MAX_MINT, INVALID_NUMBER_OF_TANS ); _; } /// @notice Require maximum one mint per address /// @dev OG and WL minters have this restriction modifier oneMint() { require( addressPreminted[_msgSender()] == false, "Only one premint allowed" ); _; } /// _ _ /// ___| |_ ___| |_ ___ /// |_ -| _| .'| _| -_| /// |___|_| |__,|_| |___| /// @notice Change to mint stage; this is an implicit action when "mint" is called when shouldPublicMintBeOpen == true /// @dev Can only be called over Chainlink VRF random response function changeStateGenerationClosed() internal virtual override generationBetween(currentGeneration, 1, 7) inEitherState(StateType.GENERATIONSTARTED, StateType.GENERATIONCLOSING) onlyTeamMemberOrOwner() { if (currentGeneration < 7) { lastGenerationSeedRequestTimestamp = 0; requestGenerationSeed(currentGeneration + 1); } emit GenerationClosed(currentGeneration); } /// @notice Change to mint stage; this is an implicit action when "mint" is called when shouldPublicMintBeOpen == true /// @dev Can only be called over Chainlink VRF random response function changeStateGenerationClosing() internal virtual override inState(StateType.GENERATIONSTARTED) onlyTangramContract() { emit GenerationClosing(currentGeneration); } /// @notice Change to mint stage; this is an implicit action when "mint" is called when shouldPublicMintBeOpen == true /// @dev Can only be called over Chainlink VRF random response function changeStateGenerationStarted() internal virtual override inEitherState(StateType.MINTCLOSED, StateType.GENERATIONCLOSED) onlyVRFCoordinator() { } /// @notice Change to mint stage; this is an implicit action when "mint" is called when shouldPublicMintBeOpen == true /// @dev Can also be called over setState method function changeStateMint() internal virtual override inState(StateType.PREMINT) onlyTeamMemberOrOwner() { } /// @notice Request Gen-1 seed, payout caller's funds /// @dev Caller's funds are only paid when this method was invoked from a team member's address; not the owner's address function changeStateMintClosed() internal virtual override inState(StateType.MINT) onlyTeamMemberOrOwner() { requestGenerationSeed(1); } /// @notice Request Gen-1 seed, payout caller's funds /// @dev Caller's funds are only paid when this method was invoked from a team member's address; not the owner's address function changeStateMintClosedAfter() internal virtual override inState(StateType.MINTCLOSED) onlyTeamMemberOrOwner() { mintCounter[1] = totalSupply(); mintBalanceTotal = address(this).balance - secondaryBalanceTotal; if (!emergencyCalled && isTeamMember(_msgSender()) && address(this).balance > 0) { payout(); } } /// @notice Change to premint stage /// @dev This is only allowed by the contract owner, either by means of deployment or later execution of setState function changeStatePremint() internal virtual override inState(StateType.DEPLOYED) onlyTeamMemberOrOwner() { } /// @notice Set new state /// @dev Use this for non-automatic state changes (e.g. open premint, close generation) /// @param _to New state to change to function setState(StateType _to) external onlyTeamMemberOrOwner() { changeState(state, _to); } /// @notice Announce generation close function setStateGenerationClosing() external onlyTangramContract() { changeState(state, StateType.GENERATIONCLOSING); } /// _ /// ___ ___ ___ _| |___ _____ ___ ___ ___ ___ /// | _| .'| | . | . | | | -_|_ -|_ -| /// |_| |__,|_|_|___|___|_|_|_|_|_|___|___|___| address private immutable vrfCoordinator; /// @notice Generation seed received, open generation /// @dev Only possibly when mint is closed or previous generation has been closed. Seed is in VRFD20.generationSeed[generation]. Event is NOT emitted from contract address. /// @param generation Generation for which seed has been received function processGenerationSeedReceived(uint generation) internal virtual override inEitherState(StateType.MINTCLOSED, StateType.GENERATIONCLOSED) onlyVRFCoordinator() { require( generation == currentGeneration + 1, "Invalid seed generation" ); currentGeneration = generation; state = StateType.GENERATIONSTARTED; // Emitting stateChanged event is useless, as this is in the VRF Coordinator's tx context } /// @notice Re-request generation seed /// @dev Only possible before starting new generation. Requests seed for the next generation. Important checks performed by internal method. function reRequestGenerationSeed() external inEitherState(StateType.MINT, StateType.GENERATIONCLOSED) onlyTeamMemberOrOwner() { requestGenerationSeed(currentGeneration + 1); } /// @notice Require that the sender is Chainlink's VRF Coordinator modifier onlyVRFCoordinator() { require( _msgSender() == vrfCoordinator, "Only VRF Coordinator" ); _; } /// _ /// ___ ___ _ _ ___ _ _| |_ /// | . | .'| | | . | | | _| /// | _|__,|_ |___|___|_| /// |_| |___| string private constant TX_FAILED = "TX failed"; /// @notice Pay out all funds directly to the emergency wallet /// @dev Only emergency payouts can be used; personal payouts are locked function emergencyPayout() external onlyTeamMemberOrOwner() { emergencyCalled = true; (bool sent,) = teamAddresses[0].call{value: address(this).balance}(""); require( sent, TX_FAILED ); } /// @notice Pay the yet unpaid funds to the caller, when it is a team member /// @dev Does not work after emergency payout was used. Implement secondary share payouts function payout() public emergencyNotCalled() inStateOrAbove(StateType.MINTCLOSED) { (bool isTeamMember, uint teamIndex) = getTeamIndex(_msgSender()); require( isTeamMember, "Invalid address" ); uint shareIndex = teamIndex * TEAM_SHARE_RECORD_SIZE; uint mintShare = 0; if (mintSharePaid[teamIndex] == false) { mintSharePaid[teamIndex] = true; mintShare = (mintBalanceTotal * teamShare[shareIndex + TEAM_SHARE_MINT_OFFSET]) / 1000; } uint secondaryShare = 0; if (secondaryBalanceTotal > teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET]) { uint secondaryShareToPay = secondaryBalanceTotal - teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET]; teamShare[shareIndex + TEAM_SHARE_SECONDARY_PAID_OFFSET] = secondaryBalanceTotal; secondaryShare = (secondaryShareToPay * teamShare[shareIndex + TEAM_SHARE_SECONDARY_OFFSET]) / 1000; } uint total = mintShare + secondaryShare; require( total > 0, "Nothing to pay" ); (bool sent,) = payable(_msgSender()).call{value: total}(""); require( sent, TX_FAILED ); } /// @notice Keep track of total secondary sales earnings receive() external payable { secondaryBalanceTotal += msg.value; } /// @notice Require emergency payout to not have been called modifier emergencyNotCalled() { require( false == emergencyCalled, "Emergency called" ); _; } /// ___ ___ ___ /// ___ ___ ___|_ |_ |_ | /// | -_| _| _| | | _|_| |_ /// |___|_| |___| |_|___|_____| /// @notice Burn token on behalf of Tangram contract /// @dev Caller needs to verify token ownership /// @param tokenId Token ID to burn function burn(uint256 tokenId) external onlyTangramContract() whenNotPaused() { _burn(tokenId); } /// @notice Return metadata url (placeholder) or base64-encoded metadata when gen-1 has started /// @dev Overridden from OpenZeppelin's implementation to skip the unused baseURI check function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "Nonexistent token" ); if (state <= StateType.MINTCLOSED) { return string(abi.encodePacked( METADATA_BASE_URI, "placeholder", JSON_EXT )); } uint generation = tangramContract.getGeneration(tokenId); require( generation <= currentGeneration, INVALID_GENERATION ); return tangramContract.getTanMetadata(tokenId, generation, generationSeed[generation]); } /// _ _ _ /// _____ ___| |_ ___ _| |___| |_ ___ /// | | -_| _| .'| . | .'| _| .'| /// |_|_|_|___|_| |__,|___|__,|_| |__,| function contractURI() public pure returns (string memory) { return string(abi.encodePacked( METADATA_BASE_URI, METADATA_CONTRACT, JSON_EXT )); } /// _ /// ___ ___ ___ ___ ___ ___| | /// | . | -_| | -_| _| .'| | /// |_ |___|_|_|___|_| |__,|_| /// |___| uint private mintBalanceTotal = 0; uint private secondaryBalanceTotal = 0; uint public currentGeneration = 0; string private constant METADATA_BASE_URI = 'https://tacticaltangrams.io/metadata/'; string private constant METADATA_CONTRACT = 'contract_tan'; string private constant JSON_EXT = '.json'; string private constant INVALID_GENERATION = "Invalid generation"; string private constant ONLY_TEAM_MEMBER = "Only team member"; modifier generationBetween(uint generation, uint from, uint to) { require( generation >= from && generation <= to, INVALID_GENERATION ); _; } /// @notice Require that the sender is a team member modifier onlyTeamMember() { require( isTeamMember(_msgSender()), ONLY_TEAM_MEMBER ); _; } /// @notice Require that the sender is a team member or the contract owner modifier onlyTeamMemberOrOwner() { require( _msgSender() == owner() || isTeamMember(_msgSender()), string(abi.encodePacked(ONLY_TEAM_MEMBER, " or owner")) ); _; } /// _ _ _____ /// ___ ___ ___| |_ ___ ___ ___| |_ |_ _|___ ___ ___ ___ ___ _____ /// | _| . | | _| _| .'| _| _| | | | .'| | . | _| .'| | /// |___|___|_|_|_| |_| |__,|___|_| |_| |__,|_|_|_ |_| |__,|_|_|_| /// |___| TangramContract tangramContract; address tangramContractAddress; /// @notice Set Tangram contract address /// @param _tangramContract Address for Tangram contract function setTangramContract(address _tangramContract) public onlyOwner() { tangramContractAddress = _tangramContract; tangramContract = TangramContract(_tangramContract); } /// @notice Require that the sender is the Tangram contract modifier onlyTangramContract() { require( _msgSender() == tangramContractAddress, "Only Tangram contract" ); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// _ _ _ _ _ _ /// | |_ ___ ___| |_|_|___ ___| | | |_ ___ ___ ___ ___ ___ _____ ___ |_|___ /// | _| .'| _| _| | _| .'| | | _| .'| | . | _| .'| |_ -| _ | | . | /// |_| |__,|___|_| |_|___|__,|_| |_| |__,|_|_|_ |_| |__,|_|_|_|___| |_| |_|___| /// |___| /// /// tacticaltangrams.io /// _ _ _____ _ _ /// ___ ___ ___| |_ ___ ___ ___| |_ | __| |_ ___| |_ ___ /// | _| . | | _| _| .'| _| _| |__ | _| .'| _| -_| /// |___|___|_|_|_| |_| |__,|___|_| |_____|_| |__,|_| |___| /// @title Tactical Tangrams State contract /// @author tacticaltangrams.io /// @notice Implements the basis for Tactical Tangram's state machine abstract contract State { /// @notice Emit state changes /// @param oldState Previous state /// @param newState Current state event StateChanged(StateType oldState, StateType newState); /// @notice Change to new state when state change is allowed /// @dev Virtual methods changeState* have to be implemented. Invalid state changes have to be reverted in each changeState* method /// @param _from State to change from /// @param _to State to change to function changeState(StateType _from, StateType _to) internal { require( (_from != _to) && (StateType.ALL == _from || state == _from), INVALID_STATE_CHANGE ); bool stateChangeHandled = false; if (StateType.PREMINT == _to) { stateChangeHandled = true; changeStatePremint(); } else if (StateType.MINT == _to) { stateChangeHandled = true; changeStateMint(); } else if (StateType.MINTCLOSED == _to) { stateChangeHandled = true; changeStateMintClosed(); } // StateType.GENERATIONSTARTED cannot be set over setState, this is done implicitly by processGenerationSeedReceived else if (StateType.GENERATIONCLOSING == _to) { stateChangeHandled = true; changeStateGenerationClosing(); } else if (StateType.GENERATIONCLOSED == _to) { stateChangeHandled = true; changeStateGenerationClosed(); } require( stateChangeHandled, INVALID_STATE_CHANGE ); state = _to; emit StateChanged(_from, _to); if (StateType.MINTCLOSED == _to) { changeStateMintClosedAfter(); } } function changeStatePremint() internal virtual; function changeStateMint() internal virtual; function changeStateMintClosed() internal virtual; function changeStateMintClosedAfter() internal virtual; function changeStateGenerationStarted() internal virtual; function changeStateGenerationClosing() internal virtual; function changeStateGenerationClosed() internal virtual; /// @notice Verify allowed states /// @param _either Allowed state /// @param _or Allowed state modifier inEitherState(StateType _either, StateType _or) { require( (state == _either) || (state == _or), INVALID_STATE ); _; } /// @notice Verify allowed state /// @param _state Allowed state modifier inState(StateType _state) { require( state == _state, INVALID_STATE ); _; } /// @notice Verify allowed minimum state /// @param _state Minimum allowed state modifier inStateOrAbove(StateType _state) { require( state >= _state, INVALID_STATE ); _; } /// @notice List of states for Tactical Tangrams /// @dev When in states GENERATIONSTARTED, GENERATIONCLOSING or GENERATIONCLOSED, Tan.currentGeneration indicates the current state enum StateType { ALL , DEPLOYED , // contract has been deployed PREMINT , // only OG and WL minting allowed MINT , // only public minting allowed MINTCLOSED , // no more minting allowed; total mint income stored, random seed for gen 1 requested GENERATIONSTARTED , // random seed available, Tans revealed GENERATIONCLOSING , // 80-100% Tans swapped GENERATIONCLOSED // 100% Tans swapped, random seed for next generation requested for gen < 7 } StateType public state = StateType.DEPLOYED; string private constant INVALID_STATE = "Invalid state"; string private constant INVALID_STATE_CHANGE = "Invalid state change"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// _ _ _ _ _ _ /// | |_ ___ ___| |_|_|___ ___| | | |_ ___ ___ ___ ___ ___ _____ ___ |_|___ /// | _| .'| _| _| | _| .'| | | _| .'| | . | _| .'| |_ -| _ | | . | /// |_| |__,|___|_| |_|___|__,|_| |_| |__,|_|_|_ |_| |__,|_|_|_|___| |_| |_|___| /// |___| /// /// tacticaltangrams.io /// _ _ /// |_|_____ ___ ___ ___| |_ ___ /// | | | . | . | _| _|_ -| /// |_|_|_|_| _|___|_| |_| |___| /// |_| import "@openzeppelin/contracts/utils/Context.sol"; /// _ _ _____ /// ___ ___ ___| |_ ___ ___ ___| |_ |_ _|___ ___ _____ /// | _| . | | _| _| .'| _| _| | | | -_| .'| | /// |___|___|_|_|_| |_| |__,|___|_| |_| |___|__,|_|_|_| /// @title Tactical Tangrams Team contract /// @author tacticaltangrams.io /// @notice Contains wallet and share details for personal payouts contract Team is Context { uint internal constant TEAM_SIZE = 4; uint internal constant TEAM_SHARE_RECORD_SIZE = 3; uint internal constant TEAM_SHARE_MINT_OFFSET = 0; uint internal constant TEAM_SHARE_SECONDARY_OFFSET = 1; uint internal constant TEAM_SHARE_SECONDARY_PAID_OFFSET = 2; /// _ _ /// ___ ___ ___ ___| |_ ___ _ _ ___| |_ ___ ___ /// | _| . | |_ -| _| _| | | _| _| . | _| /// |___|___|_|_|___|_| |_| |___|___|_| |___|_| /// @notice Deployment constructor /// @dev Initializes team addresses. Note that this is only meant for deployment flexibility; the team size and rewards are fixed in the contract /// @param _teamAddresses List of team member's addresses; first address is emergency address constructor(address payable[TEAM_SIZE] memory _teamAddresses) { for (uint teamIndex = 0; teamIndex < teamAddresses.length; teamIndex++) { teamAddresses[teamIndex] = _teamAddresses[teamIndex]; } } /// @notice Returns the team member's index based on wallet address /// @param _address Wallet address of team member /// @return (bool, index) where bool indicates whether the given address is a team member function getTeamIndex(address _address) internal view returns (bool, uint) { for (uint index = 0; index < TEAM_SIZE; index++) { if (_address == teamAddresses[index]) { return (true, index); } } return (false, 0); } /// @notice Checks whether given address is a team member /// @param _address Address to check team membership for /// @return True when _address is a team member, False otherwise function isTeamMember(address _address) internal view returns (bool) { (bool _isTeamMember,) = getTeamIndex(_address); return _isTeamMember; } /// @notice Team member's addresses /// @dev Team member information in other arrays can be found at the corresponding index. address payable[TEAM_SIZE] internal teamAddresses; /// @notice The emergency address is used when things go wrong; no personal payout is possible anymore after emergency payout bool internal emergencyCalled = false; /// @notice Mint shares are paid out only once per address, after public minting has closed bool[TEAM_SIZE] internal mintSharePaid = [ false, false, false, false ]; /// @notice Mint and secondary sales details per team member /// @dev Flattened array: [[<mint promille>, <secondary sales promille>, <secondary sales shares paid>], ..] uint[TEAM_SIZE * TEAM_SHARE_RECORD_SIZE] internal teamShare = [ 450, 287, 0, 300, 287, 0, 215, 286, 0, 35, 140, 0 ]; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// _ _ _ _ _ _ /// | |_ ___ ___| |_|_|___ ___| | | |_ ___ ___ ___ ___ ___ _____ ___ |_|___ /// | _| .'| _| _| | _| .'| | | _| .'| | . | _| .'| |_ -| _ | | . | /// |_| |__,|___|_| |_|___|__,|_| |_| |__,|_|_|_ |_| |__,|_|_|_|___| |_| |_|___| /// |___| /// /// tacticaltangrams.io /// _ _ /// |_|_____ ___ ___ ___| |_ ___ /// | | | . | . | _| _|_ -| /// |_|_|_|_| _|___|_| |_| |___| /// |_| import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; /// _ _ _____ _____ _____ ___ ___ /// ___ ___ ___| |_ ___ ___ ___| |_ | | | __ | __|_ | | /// | _| . | | _| _| .'| _| _| | | | -| __| _| | | /// |___|___|_|_|_| |_| |__,|___|_| \___/|__|__|__| |___|___| /// @title Tactical Tangrams VRP20 randomness contract /// @author tacticaltangrams.io, based on a sample taken from https://docs.chain.link/docs/chainlink-vrf/ /// @notice Requests random seed for each generation abstract contract VRFD20 is VRFConsumerBase { /// _ _ /// ___ ___ ___ ___| |_ ___ _ _ ___| |_ ___ ___ /// | _| . | |_ -| _| _| | | _| _| . | _| /// |___|___|_|_|___|_| |_| |___|___|_| |___|_| /// @notice Deployment constructor /// @dev Note that these parameter values differ per network, see https://docs.chain.link/docs/vrf-contracts/ /// @param _vrfCoordinator Chainlink VRF Coordinator address /// @param _link LINK token address /// @param _keyHash Public key against which randomness is created /// @param _fee VRF Chainlink fee in LINK constructor(address _vrfCoordinator, address _link, bytes32 _keyHash, uint _fee) VRFConsumerBase(_vrfCoordinator, _link) { keyHash = _keyHash; fee = _fee; } /// @notice Request generation seed /// @dev Only request when last request is: older than 30 minutes and (seed has not been requested or received) and (previous generation seed has been received) /// @param requestForGeneration Generation for which to request seed function requestGenerationSeed(uint requestForGeneration) internal lastGenerationSeedRequestTimedOut() { require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK" ); // Do not check whether seed has already been requested; requests can theoretically timeout require( (generationSeed[requestForGeneration] == 0) || // not requested (generationSeed[requestForGeneration] == type(uint).max), // not received "Seed already requested or received" ); // Verify that previous generation seed has been received, when applicable if (requestForGeneration > 1) { require( generationSeed[requestForGeneration-1] != type(uint).max, "Previous generation seed not received" ); } lastGenerationSeedRequestTimestamp = block.timestamp; bytes32 requestId = requestRandomness(keyHash, fee); generationSeedRequest[requestId] = requestForGeneration; generationSeed[requestForGeneration] = type(uint).max; } /// @notice Cast uint256 to bytes /// @param x Value to cast from /// @return b Bytes representation of x function toBytes(uint256 x) private pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } /// @notice Receive generation seed /// @dev Only possible when generation seed has not been received yet function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { uint generation = generationSeedRequest[requestId]; require( (generation >= 1) && (generation <= 7), "Invalid generation" ); if (generation > 1) { require( generationSeed[generation-1] != type(uint).max, "Previous generation seed not received" ); } require( generationSeed[generation] == type(uint).max, "Random number not requested or already received" ); generationSeed[generation] = randomness; generationHash[generation] = keccak256(toBytes(randomness)); processGenerationSeedReceived(generation); } /// @notice Method invoked when randomness for a valid request has been received /// @dev Implement this method in inheriting contract. Random number is stored in generationSeed[generation] /// @param generation Generation number for which random number has been received function processGenerationSeedReceived(uint generation) virtual internal; /// @notice Allow re-requesting of generation seeds after GENERATION_SEED_REQUEST_TIMEOUT (30 minutes) /// @dev In the very unlikely event that a request is never answered, re-requesting should be allowed modifier lastGenerationSeedRequestTimedOut() { require( (lastGenerationSeedRequestTimestamp + GENERATION_SEED_REQUEST_TIMEOUT) < block.timestamp, "Not timed out" ); _; } /// @notice Chainlink fee in LINK for VRF /// @dev Set this to 0.1 LINK for Rinkeby, 2 LINK for mainnet uint private immutable fee; bytes32 private immutable keyHash; uint lastGenerationSeedRequestTimestamp = 0; uint GENERATION_SEED_REQUEST_TIMEOUT = 1800; // 30 minutes request timeout mapping(bytes32 => uint) public generationSeedRequest; mapping(uint => uint) public generationSeed; mapping(uint => bytes32) public generationHash; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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; 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } }
Mint helper method All checks need to be performed before calling this method numTans number of Tans to mint
function mintLocal(uint numTans) private inEitherState(StateType.PREMINT, StateType.MINT) whenNotPaused() { for (uint mintedTan = 0; mintedTan < numTans; mintedTan++) { _mint(_msgSender(), totalSupply() + 1); } }
12,225,906
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.8.0; import "../utils/Context.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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 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 { require(hasRole(getRoleAdmin(role), _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 override { require(hasRole(getRoleAdmin(role), _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 override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } 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; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "./OndoRegistryClientInitializable.sol"; abstract contract OndoRegistryClient is OndoRegistryClientInitializable { constructor(address _registry) { __OndoRegistryClient__initialize(_registry); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "contracts/interfaces/IRegistry.sol"; import "contracts/libraries/OndoLibrary.sol"; abstract contract OndoRegistryClientInitializable is Initializable, ReentrancyGuard, Pausable { using SafeERC20 for IERC20; IRegistry public registry; uint256 public denominator; function __OndoRegistryClient__initialize(address _registry) internal initializer { require(_registry != address(0), "Invalid registry address"); registry = IRegistry(_registry); denominator = registry.denominator(); } /** * @notice General ACL checker * @param _role Role as defined in OndoLibrary */ modifier isAuthorized(bytes32 _role) { require(registry.authorized(_role, msg.sender), "Unauthorized"); _; } /* * @notice Helper to expose a Pausable interface to tools */ function paused() public view virtual override returns (bool) { return registry.paused() || super.paused(); } function pause() external virtual isAuthorized(OLib.PANIC_ROLE) { super._pause(); } function unpause() external virtual isAuthorized(OLib.GUARDIAN_ROLE) { super._unpause(); } /** * @notice Grab tokens and send to caller * @dev If the _amount[i] is 0, then transfer all the tokens * @param _tokens List of tokens * @param _amounts Amount of each token to send */ function _rescueTokens(address[] calldata _tokens, uint256[] memory _amounts) internal virtual { for (uint256 i = 0; i < _tokens.length; i++) { uint256 amount = _amounts[i]; if (amount == 0) { amount = IERC20(_tokens[i]).balanceOf(address(this)); } IERC20(_tokens[i]).safeTransfer(msg.sender, amount); } } function rescueTokens(address[] calldata _tokens, uint256[] memory _amounts) public whenPaused isAuthorized(OLib.GUARDIAN_ROLE) { require(_tokens.length == _amounts.length, "Invalid array sizes"); _rescueTokens(_tokens, _amounts); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "contracts/interfaces/ITrancheToken.sol"; import "contracts/interfaces/IRegistry.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/IWETH.sol"; /** * @title Global values used by many contracts * @notice This is mostly used for access control */ contract Registry is IRegistry, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; bool private _paused; bool public override tokenMinting; uint256 public constant override denominator = 10000; IWETH public immutable override weth; EnumerableSet.AddressSet private deadTokens; address payable public fallbackRecipient; mapping(address => string) public strategistNames; modifier onlyRole(bytes32 _role) { require(hasRole(_role, msg.sender), "Unauthorized: Invalid role"); _; } constructor( address _governance, address payable _fallbackRecipient, address _weth ) { require( _fallbackRecipient != address(0) && _fallbackRecipient != address(this), "Invalid address" ); _setupRole(DEFAULT_ADMIN_ROLE, _governance); _setupRole(OLib.GOVERNANCE_ROLE, _governance); _setRoleAdmin(OLib.VAULT_ROLE, OLib.DEPLOYER_ROLE); _setRoleAdmin(OLib.ROLLOVER_ROLE, OLib.DEPLOYER_ROLE); _setRoleAdmin(OLib.STRATEGY_ROLE, OLib.DEPLOYER_ROLE); fallbackRecipient = _fallbackRecipient; weth = IWETH(_weth); } /** * @notice General ACL check * @param _role One of the predefined roles * @param _account Address to check * @return Access/Denied */ function authorized(bytes32 _role, address _account) public view override returns (bool) { return hasRole(_role, _account); } /** * @notice Add a new official strategist * @dev grantRole protects this ACL * @param _strategist Address of new strategist * @param _name Display name for UI */ function addStrategist(address _strategist, string calldata _name) external { grantRole(OLib.STRATEGIST_ROLE, _strategist); strategistNames[_strategist] = _name; } function enableTokens() external override onlyRole(OLib.GOVERNANCE_ROLE) { tokenMinting = true; } function disableTokens() external override onlyRole(OLib.GOVERNANCE_ROLE) { tokenMinting = false; } /** * @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); /* * @notice Helper to expose a Pausable interface to tools */ function paused() public view override returns (bool) { return _paused; } /** * @notice Turn on paused variable. Everything stops! */ function pause() external override onlyRole(OLib.PANIC_ROLE) { _paused = true; emit Paused(msg.sender); } /** * @notice Turn off paused variable. Everything resumes. */ function unpause() external override onlyRole(OLib.GUARDIAN_ROLE) { _paused = false; emit Unpaused(msg.sender); } /** * @notice Manually determine which TrancheToken instances can be recycled * @dev Move into another list where createVault can delete to save gas. Done manually for safety. * @param _tokens List of tokens */ function tokensDeclaredDead(address[] calldata _tokens) external onlyRole(OLib.GUARDIAN_ROLE) { for (uint256 i = 0; i < _tokens.length; i++) { deadTokens.add(_tokens[i]); } } /** * @notice Called by createVault to delete a few dead contracts * @param _tranches Number of tranches (really, number of contracts to delete) */ function recycleDeadTokens(uint256 _tranches) external override onlyRole(OLib.VAULT_ROLE) { uint256 toRecycle = deadTokens.length() >= _tranches ? _tranches : deadTokens.length(); while (toRecycle > 0) { address last = deadTokens.at(deadTokens.length() - 1); try ITrancheToken(last).destroy(fallbackRecipient) {} catch {} deadTokens.remove(last); toRecycle -= 1; } } /** * @notice Who will get any random eth from dead tranchetokens * @param _target Receipient of ETH */ function setFallbackRecipient(address payable _target) external onlyRole(OLib.GOVERNANCE_ROLE) { fallbackRecipient = _target; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; interface IBasicVault { function isPaused() external view returns (bool); function getRegistry() external view returns (address); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/ITrancheToken.sol"; import "contracts/interfaces/IStrategy.sol"; import "contracts/interfaces/IBasicVault.sol"; interface IPairVault is IBasicVault { // Container to return Vault info to caller struct VaultView { uint256 id; Asset[] assets; IStrategy strategy; // Shared contract that interacts with AMMs address creator; // Account that calls createVault address strategist; // Has the right to call invest() and redeem(), and harvest() if strategy supports it address rollover; uint256 hurdleRate; // Return offered to senior tranche OLib.State state; // Current state of Vault uint256 startAt; // Time when the Vault is unpaused to begin accepting deposits uint256 investAt; // Time when investors can't move funds, strategist can invest uint256 redeemAt; // Time when strategist can redeem LP tokens, investors can withdraw } // Track the asset type and amount in different stages struct Asset { IERC20 token; ITrancheToken trancheToken; uint256 trancheCap; uint256 userCap; uint256 deposited; uint256 originalInvested; uint256 totalInvested; // not literal 1:1, originalInvested + proportional lp from mid-term uint256 received; uint256 rolloverDeposited; } function getState(uint256 _vaultId) external view returns (OLib.State); function createVault(OLib.VaultParams calldata _params) external returns (uint256 vaultId); function deposit( uint256 _vaultId, OLib.Tranche _tranche, uint256 _amount ) external; function depositETH(uint256 _vaultId, OLib.Tranche _tranche) external payable; function depositLp(uint256 _vaultId, uint256 _amount) external returns (uint256 seniorTokensOwed, uint256 juniorTokensOwed); function invest( uint256 _vaultId, uint256 _seniorMinOut, uint256 _juniorMinOut ) external returns (uint256, uint256); function redeem( uint256 _vaultId, uint256 _seniorMinOut, uint256 _juniorMinOut ) external returns (uint256, uint256); function withdraw(uint256 _vaultId, OLib.Tranche _tranche) external returns (uint256); function withdrawETH(uint256 _vaultId, OLib.Tranche _tranche) external returns (uint256); function withdrawLp(uint256 _vaultId, uint256 _amount) external returns (uint256, uint256); function claim(uint256 _vaultId, OLib.Tranche _tranche) external returns (uint256, uint256); function claimETH(uint256 _vaultId, OLib.Tranche _tranche) external returns (uint256, uint256); function depositFromRollover( uint256 _vaultId, uint256 _rolloverId, uint256 _seniorAmount, uint256 _juniorAmount ) external; function rolloverClaim(uint256 _vaultId, uint256 _rolloverId) external returns (uint256, uint256); function setRollover( uint256 _vaultId, address _rollover, uint256 _rolloverId ) external; function canDeposit(uint256 _vaultId) external view returns (bool); // function canTransition(uint256 _vaultId, OLib.State _state) // external // view // returns (bool); function getVaultById(uint256 _vaultId) external view returns (VaultView memory); function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche) external view returns ( uint256 position, uint256 claimableBalance, uint256 withdrawableExcess, uint256 withdrawableBalance ); function seniorExpected(uint256 _vaultId) external view returns (uint256); function getUserCaps(uint256 _vaultId) external view returns (uint256 seniorUserCap, uint256 juniorUserCap); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "contracts/interfaces/IWETH.sol"; /** * @title Global values used by many contracts * @notice This is mostly used for access control */ interface IRegistry is IAccessControl { function paused() external view returns (bool); function pause() external; function unpause() external; function tokenMinting() external view returns (bool); function denominator() external view returns (uint256); function weth() external view returns (IWETH); function authorized(bytes32 _role, address _account) external view returns (bool); function enableTokens() external; function disableTokens() external; function recycleDeadTokens(uint256 _tranches) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/IPairVault.sol"; interface IStrategy { // Additional info stored for each Vault struct Vault { IPairVault origin; // who created this Vault IERC20 pool; // the DEX pool IERC20 senior; // senior asset in pool IERC20 junior; // junior asset in pool uint256 shares; // number of shares for ETF-style mid-duration entry/exit uint256 seniorExcess; // unused senior deposits uint256 juniorExcess; // unused junior deposits } function vaults(uint256 vaultId) external view returns ( IPairVault origin, IERC20 pool, IERC20 senior, IERC20 junior, uint256 shares, uint256 seniorExcess, uint256 juniorExcess ); function addVault( uint256 _vaultId, IERC20 _senior, IERC20 _junior ) external; function addLp(uint256 _vaultId, uint256 _lpTokens) external; function removeLp( uint256 _vaultId, uint256 _shares, address to ) external; function getVaultInfo(uint256 _vaultId) external view returns (IERC20, uint256); function invest( uint256 _vaultId, uint256 _totalSenior, uint256 _totalJunior, uint256 _extraSenior, uint256 _extraJunior, uint256 _seniorMinOut, uint256 _juniorMinOut ) external returns (uint256 seniorInvested, uint256 juniorInvested); function sharesFromLp(uint256 vaultId, uint256 lpTokens) external view returns ( uint256 shares, uint256 vaultShares, IERC20 pool ); function lpFromShares(uint256 vaultId, uint256 shares) external view returns (uint256 lpTokens, uint256 vaultShares); function redeem( uint256 _vaultId, uint256 _seniorExpected, uint256 _seniorMinOut, uint256 _juniorMinOut ) external returns (uint256, uint256); function withdrawExcess( uint256 _vaultId, OLib.Tranche tranche, address to, uint256 amount ) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ITrancheToken is IERC20Upgradeable { function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; function destroy(address payable _receiver) external; } pragma solidity 0.8.3; interface IUserTriggeredReward { function invest(uint256 _amount) external; function withdraw() external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Arrays.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; //import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Helper functions */ library OLib { using Arrays for uint256[]; using OLib for OLib.Investor; // State transition per Vault. Just linear transitions. enum State {Inactive, Deposit, Live, Withdraw} // Only supports 2 tranches for now enum Tranche {Senior, Junior} struct VaultParams { address seniorAsset; address juniorAsset; address strategist; address strategy; uint256 hurdleRate; uint256 startTime; uint256 enrollment; uint256 duration; string seniorName; string seniorSym; string juniorName; string juniorSym; uint256 seniorTrancheCap; uint256 seniorUserCap; uint256 juniorTrancheCap; uint256 juniorUserCap; } struct RolloverParams { VaultParams vault; address strategist; string seniorName; string seniorSym; string juniorName; string juniorSym; } bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant PANIC_ROLE = keccak256("PANIC_ROLE"); bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE"); bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE"); bytes32 public constant STRATEGIST_ROLE = keccak256("STRATEGIST_ROLE"); bytes32 public constant VAULT_ROLE = keccak256("VAULT_ROLE"); bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE"); bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE"); // Both sums are running sums. If a user deposits [$1, $5, $3], then // userSums would be [$1, $6, $9]. You can figure out the deposit // amount be subtracting userSums[i]-userSum[i-1]. // prefixSums is the total deposited for all investors + this // investors deposit at the time this deposit is made. So at // prefixSum[0], it would be $1 + totalDeposits, where totalDeposits // could be $1000 because other investors have put in money. struct Investor { uint256[] userSums; uint256[] prefixSums; bool claimed; bool withdrawn; } /** * @dev Given the total amount invested by the Vault, we want to find * out how many of this investor's deposits were actually * used. Use findUpperBound on the prefixSum to find the point * where total deposits were accepted. For example, if $2000 was * deposited by all investors and $1000 was invested, then some * position in the prefixSum splits the array into deposits that * got in, and deposits that didn't get in. That same position * maps to userSums. This is the user's deposits that got * in. Since we are keeping track of the sums, we know at that * position the total deposits for a user was $15, even if it was * 15 $1 deposits. And we know the amount that didn't get in is * the last value in userSum - the amount that got it. * @param investor A specific investor * @param invested The total amount invested by this Vault */ function getInvestedAndExcess(Investor storage investor, uint256 invested) internal view returns (uint256 userInvested, uint256 excess) { uint256[] storage prefixSums_ = investor.prefixSums; uint256 length = prefixSums_.length; if (length == 0) { // There were no deposits. Return 0, 0. return (userInvested, excess); } uint256 leastUpperBound = prefixSums_.findUpperBound(invested); if (length == leastUpperBound) { // All deposits got in, no excess. Return total deposits, 0 userInvested = investor.userSums[length - 1]; return (userInvested, excess); } uint256 prefixSum = prefixSums_[leastUpperBound]; if (prefixSum == invested) { // Not all deposits got in, but there are no partial deposits userInvested = investor.userSums[leastUpperBound]; excess = investor.userSums[length - 1] - userInvested; } else { // Let's say some of my deposits got in. The last deposit, // however, was $100 and only $30 got in. Need to split that // deposit so $30 got in, $70 is excess. userInvested = leastUpperBound > 0 ? investor.userSums[leastUpperBound - 1] : 0; uint256 depositAmount = investor.userSums[leastUpperBound] - userInvested; if (prefixSum - depositAmount < invested) { userInvested += (depositAmount + invested - prefixSum); excess = investor.userSums[length - 1] - userInvested; } else { excess = investor.userSums[length - 1] - userInvested; } } } } /** * @title Subset of SafeERC20 from openZeppelin * * @dev Some non-standard ERC20 contracts (e.g. Tether) break * `approve` by forcing it to behave like `safeApprove`. This means * `safeIncreaseAllowance` will fail when it tries to adjust the * allowance. The code below simply adds an extra call to * `approve(spender, 0)`. */ library OndoSaferERC20 { using SafeERC20 for IERC20; function ondoSafeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; token.safeApprove(spender, 0); token.safeApprove(spender, newAllowance); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "contracts/interfaces/IStrategy.sol"; import "contracts/Registry.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/OndoRegistryClient.sol"; import "contracts/interfaces/IPairVault.sol"; /** * @title Basic LP strategy * @notice All LP strategies should inherit from this */ abstract contract BasePairLPStrategy is OndoRegistryClient, IStrategy { using SafeERC20 for IERC20; modifier onlyOrigin(uint256 _vaultId) { require( msg.sender == address(vaults[_vaultId].origin), "Unauthorized: Only Vault contract" ); _; } event Invest(uint256 indexed vault, uint256 lpTokens); event Redeem(uint256 indexed vault); event Harvest(address indexed pool, uint256 lpTokens); mapping(uint256 => Vault) public override vaults; constructor(address _registry) OndoRegistryClient(_registry) {} /** * @notice Deposit more LP tokens while Vault is invested */ function addLp(uint256 _vaultId, uint256 _amount) external virtual override whenNotPaused onlyOrigin(_vaultId) { Vault storage vault_ = vaults[_vaultId]; vault_.shares += _amount; } /** * @notice Remove LP tokens while Vault is invested */ function removeLp( uint256 _vaultId, uint256 _amount, address to ) external virtual override whenNotPaused onlyOrigin(_vaultId) { Vault storage vault_ = vaults[_vaultId]; vault_.shares -= _amount; IERC20(vault_.pool).safeTransfer(to, _amount); } /** * @notice Return the DEX pool and the amount of LP tokens */ function getVaultInfo(uint256 _vaultId) external view override returns (IERC20, uint256) { Vault storage c = vaults[_vaultId]; return (c.pool, c.shares); } /** * @notice Send excess tokens to investor */ function withdrawExcess( uint256 _vaultId, OLib.Tranche tranche, address to, uint256 amount ) external override onlyOrigin(_vaultId) { Vault storage _vault = vaults[_vaultId]; if (tranche == OLib.Tranche.Senior) { uint256 excess = _vault.seniorExcess; require(amount <= excess, "Withdrawing too much"); _vault.seniorExcess -= amount; _vault.senior.safeTransfer(to, amount); } else { uint256 excess = _vault.juniorExcess; require(amount <= excess, "Withdrawing too much"); _vault.juniorExcess -= amount; _vault.junior.safeTransfer(to, amount); } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "contracts/Registry.sol"; import "contracts/strategies/BasePairLPStrategy.sol"; import "contracts/vendor/uniswap/SushiSwapLibrary.sol"; import "contracts/vendor/sushiswap/IMasterChefV2.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/IUserTriggeredReward.sol"; /** * @title Access Sushiswap * @notice Add and remove liquidity to Sushiswap * @dev Though Sushiswap ripped off Uniswap, there is an extra step of * dealing with mining incentives. Unfortunately some of this info is * not in the Sushiswap contracts. This strategy will occasionally sell * Sushi for more senior/junior assets to reinvest as more LP. This cycle * continues: original assets -> LP -> sushi -> LP. */ contract SushiStakingV2Strategy is BasePairLPStrategy { using SafeERC20 for IERC20; using OndoSaferERC20 for IERC20; string public constant name = "Ondo MasterChefV2 Staking Strategy"; struct PoolData { uint256 pid; address[][2] pathsFromRewards; uint256 totalShares; uint256 totalLp; uint256 accRewardToken; IUserTriggeredReward extraRewardHandler; bool _isSet; // can't use pid because pid 0 is usdt/eth } mapping(address => PoolData) public pools; // Pointers to Sushiswap contracts IUniswapV2Router02 public immutable sushiRouter; IERC20 public immutable sushiToken; IMasterChefV2 public immutable masterChef; address public immutable sushiFactory; uint256 public sharesToLpRatio = 10e15; event NewPair(address indexed pool, uint256 pid); /** * @dev * @param _registry Ondo global registry * @param _router Address for UniswapV2Router02 for Sushiswap * @param _chef Sushiswap contract that handles mining incentives * @param _factory Address for UniswapV2Factory for Sushiswap * @param _sushi ERC20 contract for Sushi tokens */ constructor( address _registry, address _router, address _chef, address _factory, address _sushi ) BasePairLPStrategy(_registry) { require(_router != address(0), "Invalid address"); require(_chef != address(0), "Invalid address"); require(_factory != address(0), "Invalid address"); require(_sushi != address(0), "Invalid address"); registry = Registry(_registry); sushiRouter = IUniswapV2Router02(_router); sushiToken = IERC20(_sushi); masterChef = IMasterChefV2(_chef); sushiFactory = _factory; } /** * @notice Conversion of LP tokens to shares * @param vaultId Vault * @param lpTokens Amount of LP tokens * @return Number of shares for LP tokens * @return Total shares for this Vault * @return Sushiswap pool */ function sharesFromLp(uint256 vaultId, uint256 lpTokens) public view override returns ( uint256, uint256, IERC20 ) { Vault storage vault_ = vaults[vaultId]; PoolData storage poolData = pools[address(vault_.pool)]; return ( (lpTokens * poolData.totalShares) / poolData.totalLp, vault_.shares, vault_.pool ); } /** * @notice Conversion of shares to LP tokens * @param vaultId Vault * @param shares Amount of shares * @return Number LP tokens * @return Total shares for this Vault */ function lpFromShares(uint256 vaultId, uint256 shares) public view override returns (uint256, uint256) { Vault storage vault_ = vaults[vaultId]; PoolData storage poolData = pools[address(vault_.pool)]; return ((shares * poolData.totalLp) / poolData.totalShares, vault_.shares); } /** * @notice Add LP tokens while Vault is live * @dev Maintain the amount of lp deposited directly * @param _vaultId Vault * @param _lpTokens Amount of LP tokens */ function addLp(uint256 _vaultId, uint256 _lpTokens) external virtual override whenNotPaused onlyOrigin(_vaultId) { Vault storage vault_ = vaults[_vaultId]; PoolData storage poolData = pools[address(vault_.pool)]; (uint256 userShares, , ) = sharesFromLp(_vaultId, _lpTokens); vault_.shares += userShares; poolData.totalShares += userShares; poolData.totalLp += _lpTokens; midTermDepositLp(vault_.pool, _lpTokens); } /** * @notice Remove LP tokens while Vault is live * @dev * @param _vaultId Vault * @param _shares Number of shares * @param to Send LP tokens here */ function removeLp( uint256 _vaultId, uint256 _shares, address to ) external override whenNotPaused onlyOrigin(_vaultId) { require(to != address(0), "No zero address"); Vault storage vault_ = vaults[_vaultId]; PoolData storage poolData = pools[address(vault_.pool)]; (uint256 userLp, ) = lpFromShares(_vaultId, _shares); IERC20 rewardToken = IERC20(poolData.pathsFromRewards[1][0]); uint256 rewardTokenAmt = rewardToken.balanceOf(address(this)); masterChef.withdraw(poolData.pid, userLp, address(this)); rewardTokenAmt = rewardToken.balanceOf(address(this)) - rewardTokenAmt; if (address(poolData.extraRewardHandler) != address(0)) { rewardToken.safeTransfer( address(poolData.extraRewardHandler), rewardTokenAmt ); poolData.extraRewardHandler.invest(rewardTokenAmt); } else { poolData.accRewardToken += rewardTokenAmt; } vault_.shares -= _shares; poolData.totalShares -= _shares; poolData.totalLp -= userLp; IERC20(vault_.pool).safeTransfer(to, userLp); } // @dev harvest must be a controlled function b/c engages with uniswap // in mean time, can gain sushi rewards on sushi gained // from depositing into masterchef mid term function midTermDepositLp(IERC20 pool, uint256 _lpTokens) internal { PoolData storage poolData = pools[address(pool)]; IERC20 rewardToken = IERC20(poolData.pathsFromRewards[1][0]); uint256 rewardTokenAmt = rewardToken.balanceOf(address(this)); pool.ondoSafeIncreaseAllowance(address(masterChef), _lpTokens); masterChef.deposit(pools[address(pool)].pid, _lpTokens, address(this)); rewardTokenAmt = rewardToken.balanceOf(address(this)) - rewardTokenAmt; // in some cases such as the ETH/ALCX LP staking pool, the rewarder contract triggered by MasterChef V2 emits rewards when // the balance of LP staked in MasterChef is updated (ie. on a new deposit/withdrawal from an address with an existing balance). // (This behavior was present in the original MasterChef contract itself, though it is not in V2.) // Thus, when users deposit and withdraw LP between harvests, the rewards (not in SUSHI, but the other token) emitted to the strategy // have to be accounted for, because: // (1) we can't allow users to trigger compounding (swaps) because of flash loan vulnerability // (2) we compound only on the new rewards received from harvesting, so these "extra" rewards would be lost/stuck. // Instead, we handle this in one of two ways, on a per-pool basis: // (1) pool.accRewardToken tracks the amount of reward tokens sent to the contract by the rewarder between harvests. // Each pool has its own accRewardToken so that the "extra" rewards emitted to pools with LP deposit/withdrawal activity are not // collectivized across the strategy. // (2) these "extra" reward tokens are sent on to a secondary strategy, pool.extraRewardHandler, if there is a way to earn yield on // them without swapping, such as the Alchemix single-asset ALCX staking pool. if (address(poolData.extraRewardHandler) != address(0)) { rewardToken.safeTransfer( address(poolData.extraRewardHandler), rewardTokenAmt ); poolData.extraRewardHandler.invest(rewardTokenAmt); } else { poolData.accRewardToken += rewardTokenAmt; } } function addPool( address _pool, uint256 _pid, address[][2] memory _pathsFromRewards, address _extraRewardHandler ) external whenNotPaused isAuthorized(OLib.STRATEGIST_ROLE) { require(!pools[_pool]._isSet, "Pool already registered"); require(_pool != address(0), "Cannot be zero address"); address lpToken = masterChef.lpToken(_pid); require(lpToken == _pool, "LP Token does not match"); require( _pathsFromRewards[0][0] == address(sushiToken) && _pathsFromRewards[1][0] != address(sushiToken), "First path must be from SUSHI" ); address token0 = IUniswapV2Pair(_pool).token0(); address token1 = IUniswapV2Pair(_pool).token1(); for (uint256 i = 0; i < 2; i++) { address rewardToken = _pathsFromRewards[i][0]; if (rewardToken == token0 || rewardToken == token1) { require(_pathsFromRewards[i].length == 1, "Invalid path"); } else { address endToken = _pathsFromRewards[i][_pathsFromRewards[i].length - 1]; require(endToken == token0 || endToken == token1, "Invalid path"); } } pools[_pool].pathsFromRewards = _pathsFromRewards; pools[_pool].pid = _pid; pools[_pool]._isSet = true; pools[_pool].extraRewardHandler = IUserTriggeredReward(_extraRewardHandler); emit NewPair(_pool, _pid); } function updateRewardPath(address _pool, address[] calldata _pathFromReward) external whenNotPaused isAuthorized(OLib.STRATEGIST_ROLE) returns (bool success) { require(pools[_pool]._isSet, "Pool ID not yet registered"); address rewardToken = _pathFromReward[0]; address endToken = _pathFromReward[_pathFromReward.length - 1]; require( rewardToken != endToken || _pathFromReward.length == 1, "Invalid path" ); address token0 = IUniswapV2Pair(_pool).token0(); address token1 = IUniswapV2Pair(_pool).token1(); require( token0 != rewardToken && token1 != rewardToken, "This path should never be updated" ); require(token0 == endToken || token1 == endToken, "Invalid path"); PoolData storage poolData = pools[_pool]; if (rewardToken == address(sushiToken)) { poolData.pathsFromRewards[0] = _pathFromReward; success = true; } else if (rewardToken == poolData.pathsFromRewards[1][0]) { poolData.pathsFromRewards[1] = _pathFromReward; success = true; } else { success = false; } } function _compound(IERC20 _pool, PoolData storage _poolData) internal returns (uint256 lpAmount) { // since some pools may include SUSHI or the dual reward token in the pair, resulting // in the strategy holding withdrawable balances of those tokens for expired vaults, // we initialize the contract's balance and then take the diff after harvesting uint256 sushiAmount = sushiToken.balanceOf(address(this)); IERC20 rewardToken = IERC20(_poolData.pathsFromRewards[1][0]); uint256 rewardTokenAmount = rewardToken.balanceOf(address(this)); masterChef.harvest(_poolData.pid, address(this)); // see comments from line 207 in midtermDeposit for documentation explaining the following code if (address(_poolData.extraRewardHandler) != address(0)) { _poolData.extraRewardHandler.withdraw(); } sushiAmount = sushiToken.balanceOf(address(this)) - sushiAmount; rewardTokenAmount = rewardToken.balanceOf(address(this)) - rewardTokenAmount + _poolData.accRewardToken; _poolData.accRewardToken = 0; // to prevent new vaults from receiving a disproportionate share of the pool, this function is called by invest(). consequently, // we have to account for the case in which it is triggered by investing the first vault created for a given pool, since there will // not be any rewards after calling harvest, leave, etc. above. we constrain on 1 (10^-18) instead of 0 because of a quirk in // MasterChef's bookkeeping that can result in transferring a reward amount of 1 even if there is currently no LP balance // deposited in it. if (sushiAmount > 10000 && rewardTokenAmount > 10000) { IUniswapV2Pair pool = IUniswapV2Pair(address(_pool)); // tokenAmountsArray will keep track of the token amounts to be reinvested throughout the series of swaps, updating in place. // here, it starts as the initially harvested SUSHI and dual reward token amounts. the order semantics are fixed, and match // poolInfo.pathsFromRewards - see addPool() and updateRewardPath() above uint256[] memory tokenAmountsArray = new uint256[](2); tokenAmountsArray[0] = sushiAmount; tokenAmountsArray[1] = rewardTokenAmount; for (uint256 i = 0; i < 2; i++) { // the first element in the swap path is the reward token itself, so an array length of 1 indicates that the token // is also one of the LP assets and thus does not need to be swapped if ( tokenAmountsArray[i] > 0 && _poolData.pathsFromRewards[i].length > 1 ) { // if the reward token does need to be swapped into one of the LP assets, that harvestAmount is updated in place with // the amount of LP asset received, now representing a token amount that can be passed into addLiquidity() tokenAmountsArray[i] = swapExactIn( tokenAmountsArray[i], // internal swap calls do not set a minimum amount received, which is constrained only after compounding, on LP received 0, _poolData.pathsFromRewards[i] ); } } // since the first element of pathsFromRewards is always the SUSHI swap path, tokenA is SUSHI if that is one of the LP assets, // or otherwise the LP asset we've chosen to swap SUSHI rewards for. we use 'A' and 'B' to avoid confusion with the token0 and token1 // values of the UniswapV2Pair contract, which represent the same tokens but in a specific order that this function doesn't care about address tokenA = _poolData.pathsFromRewards[0][_poolData.pathsFromRewards[0].length - 1]; // tokenB is the other asset in the LP address tokenB = IUniswapV2Pair(address(pool)).token0(); if (tokenB == tokenA) tokenB = IUniswapV2Pair(address(pool)).token1(); // there are two cases: either both rewards (SUSHI and dual) have now been converted to amounts of the same LP asset, or to // amounts of each LP asset bool sameTarget = tokenA == _poolData.pathsFromRewards[1][ _poolData.pathsFromRewards[1].length - 1 ]; if (sameTarget) { // this is the case in which we are starting with two amounts of the same LP asset. we update the first harvestAmount in place // to contain the total amount of this asset tokenAmountsArray[0] = tokenAmountsArray[0] + tokenAmountsArray[1]; // we use Zapper's Babylonian method to calculate how much of this total needs to be swapped into the other LP asset in order to // addLiquidity without remainder. this is removed from the first harvestAmount, which now represents the final amount of tokenA // to be added to the LP, and written into the second harvestAmount, now the amount of tokenA that will be converted to tokenB (uint256 reserveA, ) = SushiSwapLibrary.getReserves(sushiFactory, tokenA, tokenB); tokenAmountsArray[1] = calculateSwapInAmount( reserveA, tokenAmountsArray[0] ); tokenAmountsArray[0] -= tokenAmountsArray[1]; // we update the second harvestAmount (amount of tokenA to be swapped) with the amount of tokenB received. tokenAmountsArray now // represents balanced LP assets that can be passed into addLiquidity without remainder, resulting in lpAmount = the final // compounding result tokenAmountsArray[1] = swapExactIn( tokenAmountsArray[1], 0, getPath(tokenA, tokenB) ); (, , lpAmount) = addLiquidity( tokenA, tokenB, tokenAmountsArray[0], tokenAmountsArray[1] ); } else { // in this branch, we have amounts of both LP assets and may need to swap in order to balance them. the zap-in method alone doesn't // suffice for this, so to avoid some very tricky and opaque math, we simply: // (1) addLiquidity, leaving remainder in at most one LP asset // (2) check for a remainder // (3) if it exists, zap this amount into balanced amounts of each LP asset // (4) addLiquidity again, leaving no remainder uint256 amountInA; uint256 amountInB; (amountInA, amountInB, lpAmount) = addLiquidity( tokenA, tokenB, tokenAmountsArray[0], tokenAmountsArray[1] ); // tokenAmountsArray are updated in place to represent the remaining LP assets after adding liquidity. at least one element is 0, // and except in the extremely rare case that the amounts were already perfectly balanced, the other element is > 0. the semantics // of which element holds a balance of which token remains fixed: [0] is tokenA, which is or was swapped from SUSHI, and [1] is tokenB, // which is or was swapped from the dual reward token, and they comprise both of the LP assets. tokenAmountsArray[0] -= amountInA; tokenAmountsArray[1] -= amountInB; require( tokenAmountsArray[0] == 0 || tokenAmountsArray[1] == 0, "Insufficient liquidity added on one side of first call" ); (uint256 reserveA, uint256 reserveB) = SushiSwapLibrary.getReserves(sushiFactory, tokenA, tokenB); // in the first branch, the entire original amount of tokenA was added to the LP and is now 0, and there is a nonzero remainder // of tokenB. we initialize the swap amount outside the conditional so that at the end we know whether we performed any swaps // and therefore need to addLiquidity a second time uint256 amountToSwap; if (tokenAmountsArray[0] < tokenAmountsArray[1]) { // we perform the zap in, swapping tokenB for a balanced amount of tokenA. once again, the harvestAmount swapped from is // decremented in place by the swap amount, now available outside the conditional scope, and the amount received from the // swap is stored in the other harvestAmount amountToSwap = calculateSwapInAmount(reserveB, tokenAmountsArray[1]); tokenAmountsArray[1] -= amountToSwap; tokenAmountsArray[0] += swapExactIn( amountToSwap, 0, getPath(tokenA, tokenB) ); } else if (tokenAmountsArray[0] > 0) { // in this branch, there is a nonzero remainder of tokenA, and none of tokenB, recalling that at most one of these // balances can be nonzero. the same zap-in procedure is applied, swapping tokenA for tokenB and updating amountToSwap and // both tokenAmountsArray. we structure this as an else-if with no further branch because if both amounts are 0, the original amounts // were perfectly balanced so we don't need to swap and addLiquidity again. amountToSwap = calculateSwapInAmount(reserveA, tokenAmountsArray[0]); tokenAmountsArray[0] -= amountToSwap; tokenAmountsArray[1] += swapExactIn( amountToSwap, 0, getPath(tokenB, tokenA) ); } if (amountToSwap > 0) { // if amountToSwap was updated in one of the branches above, we have balanced nonzero amounts of both LP assets // and need to addLiquidity again (, , uint256 moreLp) = addLiquidity( tokenA, tokenB, tokenAmountsArray[0], tokenAmountsArray[1] ); // recall that lpAmount was previously set by the first addLiquidity. if we've just received more, we add it to // get the final compounding result, which we include as a named return so that harvest() can constrain it with a // minimum that protects against flash price anomalies, whether adversarial or coincidental lpAmount += moreLp; } _poolData.totalLp += lpAmount; } } // we're back in the outermost function scope, where three cases could obtain: // (1) this is the first invest() call on this pool, so we called addLiquidity in the body of invest() and never entered // the outer conditional above // (2) we entered the first branch of the inner conditional, and zapped in a total amount of one LP asset received from // swapping both rewards // (3) we entered the second branch of the inner conditional, and added balanced liquidity of both LP assets received from // swapping each reward // in any case, the contract never holds LP tokens outside the duration of a function call, so its current LP balance is // the amount we deposit in MasterChef _pool.ondoSafeIncreaseAllowance( address(masterChef), _pool.balanceOf(address(this)) ); masterChef.deposit( _poolData.pid, _pool.balanceOf(address(this)), address(this) ); } function depositIntoChef(uint256 vaultId, uint256 _amount) internal { Vault storage vault = vaults[vaultId]; IERC20 pool = vault.pool; PoolData storage poolData = pools[address(pool)]; _compound(pool, poolData); if (poolData.totalLp == 0 || poolData.totalShares == 0) { poolData.totalShares = _amount * sharesToLpRatio; poolData.totalLp = _amount; vault.shares = _amount * sharesToLpRatio; } else { uint256 shares = (_amount * poolData.totalShares) / poolData.totalLp; poolData.totalShares += shares; vault.shares += shares; poolData.totalLp += _amount; } } function withdrawFromChef(uint256 vaultId) internal returns (uint256 lpTokens) { Vault storage vault = vaults[vaultId]; IERC20 pool = vault.pool; PoolData storage poolData = pools[address(pool)]; _compound(pool, poolData); lpTokens = vault.shares == poolData.totalShares ? poolData.totalLp : (poolData.totalLp * vault.shares) / poolData.totalShares; poolData.totalLp -= lpTokens; poolData.totalShares -= vault.shares; vault.shares = 0; masterChef.withdraw(poolData.pid, lpTokens, address(this)); return lpTokens; } /** * @notice Periodically reinvest sushi into LP tokens * @param pool Sushiswap pool to reinvest */ function harvest(address pool, uint256 minLp) external isAuthorized(OLib.STRATEGIST_ROLE) whenNotPaused returns (uint256) { PoolData storage poolData = pools[pool]; uint256 lp = _compound(IERC20(pool), poolData); require(lp >= minLp, "Exceeds maximum slippage"); emit Harvest(pool, lp); return lp; } function poolExists(IERC20 srAsset, IERC20 jrAsset) internal view returns (bool) { return IUniswapV2Factory(sushiFactory).getPair( address(srAsset), address(jrAsset) ) != address(0); } /** * @notice Register a Vault with the strategy * @param _vaultId Vault * @param _senior Asset for senior tranche * @param _junior Asset for junior tranche */ function addVault( uint256 _vaultId, IERC20 _senior, IERC20 _junior ) external override whenNotPaused nonReentrant isAuthorized(OLib.VAULT_ROLE) { require( address(vaults[_vaultId].origin) == address(0), "Vault already registered" ); require(poolExists(_senior, _junior), "Pool doesn't exist"); address pair = SushiSwapLibrary.pairFor( sushiFactory, address(_senior), address(_junior) ); require(pools[pair]._isSet, "Pool not supported"); vaults[_vaultId].origin = IPairVault(msg.sender); vaults[_vaultId].pool = IERC20(pair); vaults[_vaultId].senior = _senior; vaults[_vaultId].junior = _junior; } /** * @dev Simple wrapper around uniswap * @param amtIn Amount in * @param minOut Minimumum out * @param path Router path */ function swapExactIn( uint256 amtIn, uint256 minOut, address[] memory path ) internal returns (uint256) { IERC20(path[0]).ondoSafeIncreaseAllowance(address(sushiRouter), amtIn); return sushiRouter.swapExactTokensForTokens( amtIn, minOut, path, address(this), block.timestamp )[path.length - 1]; } function swapExactOut( uint256 amtOut, uint256 maxIn, address[] memory path ) internal returns (uint256) { IERC20(path[0]).ondoSafeIncreaseAllowance(address(sushiRouter), maxIn); return sushiRouter.swapTokensForExactTokens( amtOut, maxIn, path, address(this), block.timestamp )[0]; } function addLiquidity( address token0, address token1, uint256 amt0, uint256 amt1 ) internal returns ( uint256 out0, uint256 out1, uint256 lp ) { IERC20(token0).ondoSafeIncreaseAllowance(address(sushiRouter), amt0); IERC20(token1).ondoSafeIncreaseAllowance(address(sushiRouter), amt1); (out0, out1, lp) = sushiRouter.addLiquidity( token0, token1, amt0, amt1, 0, 0, address(this), block.timestamp ); } /** * @dev Given the total available amounts of senior and junior asset * tokens, invest as much as possible and record any excess uninvested * assets. * @param _vaultId Reference to specific Vault * @param _totalSenior Total amount available to invest into senior assets * @param _totalJunior Total amount available to invest into junior assets * @param _extraSenior Extra funds due to cap on tranche, must be returned * @param _extraJunior Extra funds due to cap on tranche, must be returned * @param _seniorMinIn Min amount expected for asset * @param _seniorMinIn Min amount expected for asset * @return seniorInvested Actual amout invested into LP tokens * @return juniorInvested Actual amout invested into LP tokens */ function invest( uint256 _vaultId, uint256 _totalSenior, uint256 _totalJunior, uint256 _extraSenior, uint256 _extraJunior, uint256 _seniorMinIn, uint256 _juniorMinIn ) external override nonReentrant whenNotPaused onlyOrigin(_vaultId) returns (uint256 seniorInvested, uint256 juniorInvested) { uint256 lpTokens; Vault storage vault_ = vaults[_vaultId]; vault_.senior.ondoSafeIncreaseAllowance(address(sushiRouter), _totalSenior); vault_.junior.ondoSafeIncreaseAllowance(address(sushiRouter), _totalJunior); (seniorInvested, juniorInvested, lpTokens) = sushiRouter.addLiquidity( address(vault_.senior), address(vault_.junior), _totalSenior, _totalJunior, _seniorMinIn, _juniorMinIn, address(this), block.timestamp ); vault_.seniorExcess = _totalSenior - seniorInvested + _extraSenior; vault_.juniorExcess = _totalJunior - juniorInvested + _extraJunior; depositIntoChef(_vaultId, lpTokens); emit Invest(_vaultId, lpTokens); } // hack to get stack down for redeem function getPath(address _token0, address _token1) internal pure returns (address[] memory path) { path = new address[](2); path[0] = _token0; path[1] = _token1; } function swapForSr( address _senior, address _junior, uint256 _seniorExpected, uint256 seniorReceived, uint256 juniorReceived ) internal returns (uint256, uint256) { uint256 seniorNeeded = _seniorExpected - seniorReceived; address[] memory jr2Sr = getPath(_junior, _senior); if ( seniorNeeded > SushiSwapLibrary.getAmountsOut(sushiFactory, juniorReceived, jr2Sr)[1] ) { seniorReceived += swapExactIn(juniorReceived, 0, jr2Sr); return (seniorReceived, 0); } else { juniorReceived -= swapExactOut(seniorNeeded, juniorReceived, jr2Sr); return (_seniorExpected, juniorReceived); } } /** * @dev Convert all LP tokens back into the pair of underlying * assets. Also convert any Sushi equally into both tranches. * The senior tranche is expecting to get paid some hurdle * rate above where they started. Here are the possible outcomes: * - If the senior tranche doesn't have enough, then sell some or * all junior tokens to get the senior to the expected * returns. In the worst case, the senior tranche could suffer * a loss and the junior tranche will be wiped out. * - If the senior tranche has more than enough, reduce this tranche * to the expected payoff. The excess senior tokens should be * converted to junior tokens. * @param _vaultId Reference to a specific Vault * @param _seniorExpected Amount the senior tranche is expecting * @param _seniorMinReceived Compute the expected seniorReceived factoring in any slippage * @param _juniorMinReceived Same, for juniorReceived * @return seniorReceived Final amount for senior tranche * @return juniorReceived Final amount for junior tranche */ function redeem( uint256 _vaultId, uint256 _seniorExpected, uint256 _seniorMinReceived, uint256 _juniorMinReceived ) external override nonReentrant whenNotPaused onlyOrigin(_vaultId) returns (uint256 seniorReceived, uint256 juniorReceived) { Vault storage vault_ = vaults[_vaultId]; { uint256 lpTokens = withdrawFromChef(_vaultId); vault_.pool.ondoSafeIncreaseAllowance(address(sushiRouter), lpTokens); (seniorReceived, juniorReceived) = sushiRouter.removeLiquidity( address(vault_.senior), address(vault_.junior), lpTokens, 0, 0, address(this), block.timestamp ); } if (seniorReceived < _seniorExpected) { (seniorReceived, juniorReceived) = swapForSr( address(vault_.senior), address(vault_.junior), _seniorExpected, seniorReceived, juniorReceived ); } else { if (seniorReceived > _seniorExpected) { juniorReceived += swapExactIn( seniorReceived - _seniorExpected, 0, getPath(address(vault_.senior), address(vault_.junior)) ); } seniorReceived = _seniorExpected; } require( _seniorMinReceived <= seniorReceived && _juniorMinReceived <= juniorReceived, "Exceeds maximum slippage" ); vault_.senior.ondoSafeIncreaseAllowance( msg.sender, seniorReceived + vault_.seniorExcess ); vault_.junior.ondoSafeIncreaseAllowance( msg.sender, juniorReceived + vault_.juniorExcess ); emit Redeem(_vaultId); return (seniorReceived, juniorReceived); } /** * @notice Exactly how much of userIn to swap to get perfectly balanced ratio for LP tokens * @dev This code is cloned from L1242-1253 of UniswapV2_ZapIn_General_V4 at https://etherscan.io/address/0x5ACedBA6C402e2682D312a7b4982eda0Ccf2d2E3#code#L1242 * @param reserveIn Amount of reserves for asset 0 * @param userIn Availabe amount of asset 0 to swap * @return Amount of userIn to swap for asset 1 */ function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) internal pure returns (uint256) { return (Babylonian.sqrt(reserveIn * (userIn * 3988000 + reserveIn * 3988009)) - reserveIn * 1997) / 1994; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./IRewarder.sol"; interface IMasterChefV2 { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } function poolInfo(uint256 pid) external view returns (IMasterChefV2.PoolInfo memory); function lpToken(uint256 pid) external view returns (address); function poolLength() external view returns (uint256 pools); function totalAllocPoint() external view returns (uint256); function sushiPerBlock() external view returns (uint256); function deposit( uint256 _pid, uint256 _amount, address _to ) external; function withdraw( uint256 _pid, uint256 _amount, address _to ) external; function withdrawAndHarvest( uint256 _pid, uint256 _amount, address _to ) external; function harvest(uint256 _pid, address _to) external; function userInfo(uint256 _pid, address _user) external view returns (uint256 amount, uint256 rewardDebt); /** * @dev for testing purposes via impersonateAccount * TODO: Does this need to be here? Remove it? */ function owner() external view returns (address); function add( uint256 _allocPoint, IERC20 _lpToken, IRewarder _rewarder ) external; function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool _overwrite ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRewarder { function onSushiReward( uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount ) external; function pendingTokens( uint256 pid, address user, uint256 sushiAmount ) external view returns (IERC20[] memory, uint256[] memory); } pragma solidity >=0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; library SushiSwapLibrary { using SafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
Register a Vault with the strategy _vaultId Vault _senior Asset for senior tranche _junior Asset for junior tranche/
function addVault( uint256 _vaultId, IERC20 _senior, IERC20 _junior ) external override whenNotPaused nonReentrant isAuthorized(OLib.VAULT_ROLE) { require( address(vaults[_vaultId].origin) == address(0), "Vault already registered" ); require(poolExists(_senior, _junior), "Pool doesn't exist"); address pair = SushiSwapLibrary.pairFor( sushiFactory, address(_senior), address(_junior) ); require(pools[pair]._isSet, "Pool not supported"); vaults[_vaultId].origin = IPairVault(msg.sender); vaults[_vaultId].pool = IERC20(pair); vaults[_vaultId].senior = _senior; vaults[_vaultId].junior = _junior; }
9,889,778
// SPDX-License-Identifier: Unlicense // Contract derived from etherscan at: https://etherscan.io/address/0x3aee59ca9cea21389d167112091ceace86747124#code // All rights reserved to the author. pragma solidity ^0.8.13; // Base libraries import "./SVG.sol"; import "./Utils.sol"; import "./WatchData.sol"; import "./DateTime.sol"; import "./Base64.sol"; import "./Metadata.sol"; // Component libraries import "./Bezel.sol"; import "./Face.sol"; import "./Hands.sol"; import "./Glasses.sol"; import "./Mood.sol"; import "./GlowInTheDark.sol"; interface IDefaultResolver { function name(bytes32 node) external view returns (string memory); } interface IReverseRegistrar { function node(address addr) external view returns (bytes32); function defaultResolver() external view returns (IDefaultResolver); } // Core Renderer called from the main contract. It takes in a Watchface configuration // and pulls together every component's individual library to render the final Watchface. contract SvgRenderer { struct WatchConfiguration { uint8 bezelId; uint8 faceId; uint8 moodId; uint8 glassesId; } uint256 constant BEZEL_PART_BASE = 1000000; uint256 constant FACE_PART_BASE = 10000; uint256 constant MOOD_PART_BASE = 100; uint256 constant GLASSES_PART_BASE = 1; function render( uint256 _tokenId, address _owner, uint256 _timestamp, uint256 _holdingProgress, string calldata _engraving ) public view returns (string memory) { string memory ensName = lookupENSName(_owner); WatchConfiguration memory configuration = parseTokenId(_tokenId); string memory raw = renderSVG( configuration, _owner, ensName, _timestamp, _holdingProgress, _engraving ); return string.concat( "data:application/json;base64,", Base64.encode( bytes( Metadata.getWatchfaceJSON( configuration.bezelId, configuration.faceId, configuration.moodId, configuration.glassesId, _holdingProgress, _engraving, // image data Base64.encode(bytes(raw)) ) ) ) ); } function parseTokenId(uint256 _tokenId) internal pure returns (WatchConfiguration memory configuration) { require(_tokenId / 100000000 == 0, "Token id too large"); configuration.bezelId = uint8((_tokenId / BEZEL_PART_BASE) % 100); configuration.faceId = uint8((_tokenId / FACE_PART_BASE) % 100); configuration.moodId = uint8((_tokenId / MOOD_PART_BASE) % 100); configuration.glassesId = uint8((_tokenId / GLASSES_PART_BASE) % 100); } function renderSVG( WatchConfiguration memory _config, address _owner, string memory _ensName, uint256 _timestamp, uint256 _holdingProgress, string memory _engraving ) public pure returns (string memory) { require( utils.utfStringLength(_engraving) <= 20, "Engraving must be less than or equal to 20 chars" ); Date memory ts = DateTime.timestampToDateTime(_timestamp); bool isGlowInTheDark = _config.moodId == WatchData.GLOW_IN_THE_DARK_ID && _config.glassesId == WatchData.GLOW_IN_THE_DARK_ID; bool lightFace = WatchData.MaterialId(_config.faceId) == WatchData.MaterialId.Pearl; return string.concat( // primary container '<svg xmlns="http://www.w3.org/2000/svg" width="384" height="384" style="background:#000">', // embed the primary SVG inside to simulate padding '<svg width="360" height="360" x="12" y="12">', /* render each component stacked on top of each other. 1. Bezel 2. Face (includes engraving and date) 3. Mood 4. Glasses 5. Hands 6. Overlays for color */ string.concat( Bezel.render(_owner, _ensName, _holdingProgress), Face.render(ts.day, ts.month, ts.year, _engraving, lightFace), // render custom mood for GITD. isGlowInTheDark ? GlowInTheDark.renderMood() : Mood.render(_config.moodId), // render custom glasses for GITD. isGlowInTheDark ? GlowInTheDark.renderGlasses() : Glasses.render(_config.glassesId), Hands.render(ts.second, ts.minute, ts.hour), // GITD has no diamond overlay // TODO: check if you need to see GITD status before this renderDiamondOverlay(_config) ), "</svg>", // global styles and defs generateDefs(), generateCssVars( _config.bezelId, _config.faceId, // pass in whether it's glow in the dark to // generate appropriate light / dark mode tokens. isGlowInTheDark ), "</svg>" ); } function renderDiamondOverlay(WatchConfiguration memory _config) internal pure returns (string memory) { bool hasDiamondBezel = WatchData.MaterialId(_config.bezelId) == WatchData.MaterialId.Diamond; bool hasDiamondFace = WatchData.MaterialId(_config.faceId) == WatchData.MaterialId.Diamond; bool hasPearl = WatchData.MaterialId(_config.bezelId) == WatchData.MaterialId.Pearl || WatchData.MaterialId(_config.faceId) == WatchData.MaterialId.Pearl; if (hasDiamondBezel && hasDiamondFace) { return DiamondOverlay(WatchData.OUTER_BEZEL_RADIUS, "1.0"); } else if (hasDiamondBezel || hasDiamondFace) { return DiamondOverlay(WatchData.OUTER_BEZEL_RADIUS, "0.75"); } else if (hasPearl) { return DiamondOverlay(WatchData.OUTER_BEZEL_RADIUS, "0.5"); } return utils.NULL; } function DiamondOverlay(uint256 _radius, string memory _opacity) internal pure returns (string memory) { return svg.circle( string.concat( svg.prop("r", utils.uint2str(_radius)), svg.prop("cx", utils.uint2str(WatchData.CENTER)), svg.prop("cy", utils.uint2str(WatchData.CENTER)), svg.prop("fill", utils.getDefURL("diamondOverlay")), svg.prop("filter", utils.getDefURL("blur")), svg.prop( "style", string.concat("mix-blend-mode:overlay;opacity:", _opacity, ";") ) ), utils.NULL ); } function generateDefs() internal pure returns (string memory) { return ( string.concat("<defs>", generateGradients(), generateFilters(), "</defs>") ); } function generateGradients() internal pure returns (string memory) { string memory commonGradientProps = string.concat( svg.prop("cx", "0"), svg.prop("cy", "0"), svg.prop("r", utils.uint2str(WatchData.WATCH_SIZE)), svg.prop("gradientUnits", "userSpaceOnUse") ); return string.concat( // Outer bezel gradient svg.radialGradient( string.concat( svg.prop("id", "obg"), commonGradientProps, svg.prop("gradientTransform", "scale(1)") ), string.concat( svg.gradientStop(0, utils.getCssVar("bp"), utils.NULL), svg.gradientStop(100, utils.getCssVar("bs"), utils.NULL) ) ), // Inner bezel gradient svg.radialGradient( string.concat( svg.prop("id", "ibg"), commonGradientProps, svg.prop("gradientTransform", "scale(1.5) rotate(30 180 180)") ), string.concat( svg.gradientStop(0, utils.getCssVar("bp"), utils.NULL), svg.gradientStop(100, utils.getCssVar("bs"), utils.NULL) ) ), // Face gradient svg.radialGradient( string.concat(svg.prop("id", "fg"), commonGradientProps), string.concat( svg.gradientStop(0, utils.getCssVar("fp"), utils.NULL), svg.gradientStop(100, utils.getCssVar("fs"), utils.NULL) ) ), // Reflection gradient svg.linearGradient( string.concat(svg.prop("id", "rg"), commonGradientProps), string.concat( svg.gradientStop( 0, utils.getCssVar("bs"), svg.prop("stop-opacity", "0%") ), svg.gradientStop( 50, utils.getCssVar("ba"), svg.prop("stop-opacity", "60%") ), svg.gradientStop( 100, utils.getCssVar("bs"), svg.prop("stop-opacity", "0%") ) ) ), // Gradient for monolens gradient svg.linearGradient( string.concat( svg.prop("id", "ml"), svg.prop("x1", "87"), svg.prop("y1", "137"), svg.prop("x2", "273"), svg.prop("y2", "137"), svg.prop("gradientUnits", "userSpaceOnUse") ), string.concat( svg.gradientStop(0, "#6DF7A5", utils.NULL), svg.gradientStop(50, "#5400BF", utils.NULL), svg.gradientStop(100, "#6DEFF7", utils.NULL) ) ), // // Shadow gradient svg.radialGradient( string.concat( svg.prop("id", "sg"), // center/2 svg.prop("cx", "90"), // center/2 svg.prop("cy", "90"), svg.prop("r", utils.uint2str(WatchData.WATCH_SIZE)), svg.prop("gradientUnits", "userSpaceOnUse") ), string.concat( svg.gradientStop( 0, utils.getCssVar("black"), svg.prop("stop-opacity", "0%") ), svg.gradientStop( 50, utils.getCssVar("black"), svg.prop("stop-opacity", "5%") ), svg.gradientStop( 100, utils.getCssVar("black"), svg.prop("stop-opacity", "50%") ) ) ), // Diamond overlay generateDiamondGradient() ); } function generateDiamondGradient() internal pure returns (string memory) { string[7] memory overlayGradient = WatchData.getDiamondOverlayGradient(); return svg.linearGradient( string.concat( svg.prop("id", "diamondOverlay"), svg.prop("cx", "0"), svg.prop("cy", "0"), svg.prop("r", "180"), svg.prop("gradientUnits", "userSpaceOnUse") ), string.concat( svg.gradientStop(0, overlayGradient[0], utils.NULL), svg.gradientStop(14, overlayGradient[1], utils.NULL), svg.gradientStop(28, overlayGradient[2], utils.NULL), svg.gradientStop(42, overlayGradient[3], utils.NULL), svg.gradientStop(57, overlayGradient[4], utils.NULL), svg.gradientStop(71, overlayGradient[5], utils.NULL), svg.gradientStop(85, overlayGradient[6], utils.NULL) ) ); } function generateFilters() internal pure returns (string memory) { string memory filterUnits = svg.prop("filterUnits", "userSpaceOnUse"); return string.concat( // FILTERS // Inset shadow svg.filter( string.concat(svg.prop("id", "insetShadow"), filterUnits), string.concat( svg.el( "feColorMatrix", string.concat( svg.prop("in", "SourceGraphic"), svg.prop("type", "matrix"), // that second to last value is the opacity of the matrix. svg.prop("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.7 0"), svg.prop("result", "opaque-source") ), utils.NULL ), svg.el( "feOffset", string.concat( svg.prop("in", "SourceGraphic"), svg.prop("dx", "2"), svg.prop("dy", "0") ), utils.NULL ), svg.el("feGaussianBlur", svg.prop("stdDeviation", "6"), utils.NULL), svg.el( "feComposite", string.concat( svg.prop("operator", "xor"), svg.prop("in2", "opaque-source") ), utils.NULL ), svg.el( "feComposite", string.concat( svg.prop("operator", "in"), svg.prop("in2", "opaque-source") ), utils.NULL ), svg.el( "feComposite", string.concat( svg.prop("operator", "over"), svg.prop("in2", "SourceGraphic") ), utils.NULL ) ) ), // Drop shadow svg.filter( string.concat(svg.prop("id", "dropShadow"), filterUnits), svg.el( "feDropShadow", string.concat( svg.prop("dx", "0"), svg.prop("dy", "0"), svg.prop("stdDeviation", "8"), svg.prop("floodOpacity", "0.5") ), utils.NULL ) ), // Blur svg.filter( svg.prop("id", "blur"), svg.el( "feGaussianBlur", string.concat( svg.prop("in", "SourceGraphic"), svg.prop("stdDeviation", "8") ), utils.NULL ) ) ); } function generateCssVars( uint256 _bezelId, uint256 _faceId, bool _isGlowInTheDark ) internal pure returns (string memory) { // given an ID, generate the proper variables // query the mapping WatchData.Material memory bezelMaterial = WatchData.getMaterial(_bezelId); WatchData.Material memory faceMaterial = WatchData.getMaterial(_faceId); return string.concat( "<style>", _isGlowInTheDark ? (GlowInTheDark.generateMaterialTokens()) : ( string.concat( "*{", generateMaterialTokens(bezelMaterial, faceMaterial), "}" ) ), // constant for both glow in the dark and regular colors. "*{", generateTypographyTokens(), generateConstantTokens(), "}", // Used for full progress watches. "@keyframes fadeOpacity{0%{opacity:1;} 50%{opacity:0;} 100%{opacity:1;}}", "</style>" ); } function generateMaterialTokens( WatchData.Material memory _bezelMaterial, WatchData.Material memory _faceMaterial ) internal pure returns (string memory) { return string.concat( // BEZEL COLORS // bezel primary (bp) utils.setCssVar("bp", _bezelMaterial.vals[0]), // bezel secondary (bs) utils.setCssVar("bs", _bezelMaterial.vals[1]), // bezel accent (ba) utils.setCssVar( "ba", WatchData.getMaterialAccentColor(_bezelMaterial.id) ), // FACE COLORS // face primary (fp) utils.setCssVar("fp", _faceMaterial.vals[0]), // face secondary (fs) utils.setCssVar("fs", _faceMaterial.vals[1]), // face accent (fa) utils.setCssVar( "fa", WatchData.getMaterialAccentColor(_faceMaterial.id) ) ); } function generateTypographyTokens() internal pure returns (string memory) { return string.concat( // // typography // // bezel type size // the type size is 11.65px so that on average the space between characters around the bezel is an integer (7 px). // this helps with the rendering code inside of Bezel.sol because we need to calcualte the exact spacing dynamically // and can't use decimals easily. utils.setCssVar("bts", "11.65px"), // // face type size utils.setCssVar("fts", "12px"), // // text shadow utils.setCssVar("textShadow", "1px 0 6px rgba(0,0,0,0.8)") ); } function generateConstantTokens() internal pure returns (string memory) { return string.concat( // constant colors utils.setCssVar("white", "#fff"), utils.setCssVar("black", "#000"), utils.setCssVar("clear", "transparent"), // More constants "font-family: monospace;", "font-weight: 500;", // Allows the glow to escape from the container "overflow: visible;" ); } function lookupENSName(address _address) internal view returns (string memory) { address NEW_ENS_MAINNET = 0x084b1c3C81545d370f3634392De611CaaBFf8148; address OLD_ENS_MAINNET = 0x9062C0A6Dbd6108336BcBe4593a3D1cE05512069; address ENS_RINKEBY = 0x6F628b68b30Dc3c17f345c9dbBb1E483c2b7aE5c; string memory ens = tryLookupENSName(NEW_ENS_MAINNET, _address); if (bytes(ens).length == 0) { ens = tryLookupENSName(OLD_ENS_MAINNET, _address); } if (bytes(ens).length == 0) { ens = tryLookupENSName(ENS_RINKEBY, _address); } return ens; } function tryLookupENSName(address _registrar, address _address) internal view returns (string memory) { uint32 size; assembly { size := extcodesize(_registrar) } if (size == 0) { return ""; } IReverseRegistrar ensReverseRegistrar = IReverseRegistrar(_registrar); bytes32 node = ensReverseRegistrar.node(_address); return ensReverseRegistrar.defaultResolver().name(node); } }
typography bezel type size the type size is 11.65px so that on average the space between characters around the bezel is an integer (7 px). this helps with the rendering code inside of Bezel.sol because we need to calcualte the exact spacing dynamically and can't use decimals easily. face type size text shadow
function generateTypographyTokens() internal pure returns (string memory) { return string.concat( utils.setCssVar("bts", "11.65px"), utils.setCssVar("fts", "12px"), utils.setCssVar("textShadow", "1px 0 6px rgba(0,0,0,0.8)") ); }
6,390,321
./full_match/1/0x39775AF970759966a6eB30020bD0f77Ef856d21A/sources/DigitalSecurities/FLA.sol
the remaining number of tokens that `_spender` will be allowed to spend on behalf of `_owner` through {transferFrom}. This is zero by default. _owner Owner of tokens. _spender Spender of tokens./
function allowance(address _owner, address _spender) public view virtual override returns (uint256) { return _allowances[_owner][_spender].mul(_k).div(10**_kDecimals); }
4,923,563
pragma solidity 0.4.25; // File: contracts/LinkedListLib.sol /** * @title LinkedListLib * @author Darryl Morris (o0ragman0o) and Modular.network * * This utility library was forked from https://github.com/o0ragman0o/LibCLL * into the Modular-Network ethereum-libraries repo at https://github.com/Modular-Network/ethereum-libraries * It has been updated to add additional functionality and be more compatible with solidity 0.4.18 * coding patterns. * * version 1.1.1 * Copyright (c) 2017 Modular Inc. * The MIT License (MIT) * https://github.com/Modular-network/ethereum-libraries/blob/master/LICENSE * * The LinkedListLib provides functionality for implementing data indexing using * a circlular linked list * * Modular provides smart contract services and security reviews for contract * deployments in addition to working on open source projects in the Ethereum * community. Our purpose is to test, document, and deploy reusable code onto the * blockchain and improve both security and usability. We also educate non-profits, * schools, and other community members about the application of blockchain * technology. For further information: modular.network * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library LinkedListLib { uint256 constant NULL = 0; uint256 constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList{ mapping (uint256 => mapping (bool => uint256)) list; } /// @dev returns true if the list exists /// @param self stored linked list from contract function listExists(LinkedList storage self) public view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) { return true; } else { return false; } } /// @dev returns true if the node exists /// @param self stored linked list from contract /// @param _node a node to search for function nodeExists(LinkedList storage self, uint256 _node) public view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /// @dev Returns the number of elements in the list /// @param self stored linked list from contract function sizeOf(LinkedList storage self) public view returns (uint256 numElements) { bool exists; uint256 i; (exists,i) = getAdjacent(self, HEAD, NEXT); while (i != HEAD) { (exists,i) = getAdjacent(self, i, NEXT); numElements++; } return; } /// @dev Returns the links of a node as a tuple /// @param self stored linked list from contract /// @param _node id of the node to get function getNode(LinkedList storage self, uint256 _node) public view returns (bool,uint256,uint256) { if (!nodeExists(self,_node)) { return (false,0,0); } else { return (true,self.list[_node][PREV], self.list[_node][NEXT]); } } /// @dev Returns the link of a node `_node` in direction `_direction`. /// @param self stored linked list from contract /// @param _node id of the node to step from /// @param _direction direction to step in function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) public view returns (bool,uint256) { if (!nodeExists(self,_node)) { return (false,0); } else { return (true,self.list[_node][_direction]); } } /// @dev Can be used before `insert` to build an ordered list /// @param self stored linked list from contract /// @param _node an existing node to search from, e.g. HEAD. /// @param _value value to seek /// @param _direction direction to seek in // @return next first node beyond '_node' in direction `_direction` function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) public view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self,_node)); bool exists; uint256 next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } /// @dev Creates a bidirectional link between two nodes on direction `_direction` /// @param self stored linked list from contract /// @param _node first node for linking /// @param _link node to link to in the _direction function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /// @dev Insert node `_new` beside existing node `_node` in direction `_direction`. /// @param self stored linked list from contract /// @param _node existing node /// @param _new new node to insert /// @param _direction direction to insert node in function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); return true; } else { return false; } } /// @dev removes an entry from the linked list /// @param self stored linked list from contract /// @param _node node to remove from the list function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; return _node; } /// @dev pushes an enrty to the head of the linked list /// @param self stored linked list from contract /// @param _node new entry to push to the head /// @param _direction push to the head (NEXT) or tail (PREV) function push(LinkedList storage self, uint256 _node, bool _direction) internal { insert(self, HEAD, _node, _direction); } /// @dev pops the first entry from the linked list /// @param self stored linked list from contract /// @param _direction pop from the head (NEXT) or the tail (PREV) function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/ownership/rbac/Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } // File: openzeppelin-solidity/contracts/ownership/rbac/RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * @dev Supports unlimited numbers of roles and addresses. * @dev See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: openzeppelin-solidity/contracts/ownership/Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { checkRole(msg.sender, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public { addRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressAdded(addr); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address addr) public view returns (bool) { return hasRole(addr, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { addAddressToWhitelist(addrs[i]); } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public { removeRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressRemoved(addr); } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { removeAddressFromWhitelist(addrs[i]); } } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/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: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } // File: contracts/token_escrow/TokenEscrow.sol /** * NOTE: All contracts in this directory were taken from a non-master branch of openzeppelin-solidity. * This contract was modified to be a whitelist. * Commit: ed451a8688d1fa7c927b27cec299a9726667d9b1 */ pragma solidity ^0.4.24; /** * @title TokenEscrow * @dev Holds tokens destinated to a payee until they withdraw them. * The contract that uses the TokenEscrow as its payment method * should be its owner, and provide public methods redirecting * to the TokenEscrow's deposit and withdraw. * Moreover, the TokenEscrow should also be allowed to transfer * tokens from the payer to itself. */ contract TokenEscrow is Ownable, Whitelist { using SafeMath for uint256; using SafeERC20 for ERC20; event Deposited(address indexed payee, uint256 tokenAmount); event Withdrawn(address indexed payee, uint256 tokenAmount); mapping(address => uint256) public deposits; ERC20 public token; constructor (ERC20 _token) public { require(_token != address(0)); token = _token; } function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Puts in escrow a certain amount of tokens as credit to be withdrawn. * @param _payee The destination address of the tokens. * @param _amount The amount of tokens to deposit in escrow. */ function deposit(address _payee, uint256 _amount) public onlyWhitelisted { deposits[_payee] = deposits[_payee].add(_amount); token.safeTransferFrom(msg.sender, address(this), _amount); emit Deposited(_payee, _amount); } /** * @dev Withdraw accumulated tokens for a payee. * @param _payee The address whose tokens will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyWhitelisted { uint256 payment = deposits[_payee]; assert(token.balanceOf(address(this)) >= payment); deposits[_payee] = 0; token.safeTransfer(_payee, payment); emit Withdrawn(_payee, payment); } } // File: contracts/token_escrow/ConditionalTokenEscrow.sol /** * NOTE: All contracts in this directory were taken from a non-master branch of openzeppelin-solidity. * Commit: ed451a8688d1fa7c927b27cec299a9726667d9b1 */ pragma solidity ^0.4.24; /** * @title ConditionalTokenEscrow * @dev Base abstract escrow to only allow withdrawal of tokens * if a condition is met. */ contract ConditionalTokenEscrow is TokenEscrow { /** * @dev Returns whether an address is allowed to withdraw their tokens. * To be implemented by derived contracts. * @param _payee The destination address of the tokens. */ function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } // File: contracts/QuantstampAuditTokenEscrow.sol contract QuantstampAuditTokenEscrow is ConditionalTokenEscrow { // the escrow maintains the list of staked addresses using LinkedListLib for LinkedListLib.LinkedList; // constants used by LinkedListLib uint256 constant internal NULL = 0; uint256 constant internal HEAD = 0; bool constant internal PREV = false; bool constant internal NEXT = true; // maintain the number of staked nodes // saves gas cost over needing to call stakedNodesList.sizeOf() uint256 public stakedNodesCount = 0; // the minimum amount of wei-QSP that must be staked in order to be a node uint256 public minAuditStake = 10000 * (10 ** 18); // if true, the payee cannot currently withdraw their funds mapping(address => bool) public lockedFunds; // if funds are locked, they may be retrieved after this block // if funds are unlocked, the number should be ignored mapping(address => uint256) public unlockBlockNumber; // staked audit nodes -- needed to inquire about audit node statistics, such as min price // this list contains all nodes that have *ANY* stake, however when getNextStakedNode is called, // it skips nodes that do not meet the minimum stake. // the reason for this approach is that if the owner lowers the minAuditStake, // we must be aware of any node with a stake. LinkedListLib.LinkedList internal stakedNodesList; event Slashed(address addr, uint256 amount); event StakedNodeAdded(address addr); event StakedNodeRemoved(address addr); // the constructor of TokenEscrow requires an ERC20, not an address constructor(address tokenAddress) public TokenEscrow(ERC20(tokenAddress)) {} // solhint-disable no-empty-blocks /** * @dev Puts in escrow a certain amount of tokens as credit to be withdrawn. * Overrides the function in TokenEscrow.sol to add the payee to the staked list. * @param _payee The destination address of the tokens. * @param _amount The amount of tokens to deposit in escrow. */ function deposit(address _payee, uint256 _amount) public onlyWhitelisted { super.deposit(_payee, _amount); if (_amount > 0) { // fails gracefully if the node already exists addNodeToStakedList(_payee); } } /** * @dev Withdraw accumulated tokens for a payee. * Overrides the function in TokenEscrow.sol to remove the payee from the staked list. * @param _payee The address whose tokens will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyWhitelisted { super.withdraw(_payee); removeNodeFromStakedList(_payee); } /** * @dev Sets the minimum stake to a new value. * @param _value The new value. _value must be greater than zero in order for the linked list to be maintained correctly. */ function setMinAuditStake(uint256 _value) public onlyOwner { require(_value > 0); minAuditStake = _value; } /** * @dev Returns true if the sender staked enough. * @param addr The address to check. */ function hasEnoughStake(address addr) public view returns(bool) { return depositsOf(addr) >= minAuditStake; } /** * @dev Overrides ConditionalTokenEscrow function. If true, funds may be withdrawn. * @param _payee The address that wants to withdraw funds. */ function withdrawalAllowed(address _payee) public view returns (bool) { return !lockedFunds[_payee] || unlockBlockNumber[_payee] < block.number; } /** * @dev Prevents the payee from withdrawing funds. * @param _payee The address that will be locked. */ function lockFunds(address _payee, uint256 _unlockBlockNumber) public onlyWhitelisted returns (bool) { lockedFunds[_payee] = true; unlockBlockNumber[_payee] = _unlockBlockNumber; return true; } /** * @dev Slash a percentage of the stake of an address. * The percentage is taken from the minAuditStake, not the total stake of the address. * The caller of this function receives the slashed QSP. * If the current stake does not cover the slash amount, the full stake is taken. * * @param addr The address that will be slashed. * @param percentage The percent of the minAuditStake that should be slashed. */ function slash(address addr, uint256 percentage) public onlyWhitelisted returns (uint256) { require(0 <= percentage && percentage <= 100); uint256 slashAmount = getSlashAmount(percentage); uint256 balance = depositsOf(addr); if (balance < slashAmount) { slashAmount = balance; } // subtract from the deposits amount of the addr deposits[addr] = deposits[addr].sub(slashAmount); emit Slashed(addr, slashAmount); // if the deposits of the address are now zero, remove from the list if (depositsOf(addr) == 0) { removeNodeFromStakedList(addr); } // transfer the slashAmount to the police contract token.safeTransfer(msg.sender, slashAmount); return slashAmount; } /** * @dev Returns the slash amount for a given percentage. * @param percentage The percent of the minAuditStake that should be slashed. */ function getSlashAmount(uint256 percentage) public view returns (uint256) { return (minAuditStake.mul(percentage)).div(100); } /** * @dev Given a staked address, returns the next address from the list that meets the minAuditStake. * @param addr The staked address. * @return The next address in the list. */ function getNextStakedNode(address addr) public view returns(address) { bool exists; uint256 next; (exists, next) = stakedNodesList.getAdjacent(uint256(addr), NEXT); // only return addresses that meet the minAuditStake while (exists && next != HEAD && !hasEnoughStake(address(next))) { (exists, next) = stakedNodesList.getAdjacent(next, NEXT); } return address(next); } /** * @dev Adds an address to the stakedNodesList. * @param addr The address to be added to the list. * @return true if the address was added to the list. */ function addNodeToStakedList(address addr) internal returns(bool success) { if (stakedNodesList.insert(HEAD, uint256(addr), PREV)) { stakedNodesCount++; emit StakedNodeAdded(addr); success = true; } } /** * @dev Removes an address from the stakedNodesList. * @param addr The address to be removed from the list. * @return true if the address was removed from the list. */ function removeNodeFromStakedList(address addr) internal returns(bool success) { if (stakedNodesList.remove(uint256(addr)) != 0) { stakedNodesCount--; emit StakedNodeRemoved(addr); success = true; } } }
Puts in escrow a certain amount of tokens as credit to be withdrawn. _payee The destination address of the tokens. _amount The amount of tokens to deposit in escrow./
function deposit(address _payee, uint256 _amount) public onlyWhitelisted { deposits[_payee] = deposits[_payee].add(_amount); token.safeTransferFrom(msg.sender, address(this), _amount); emit Deposited(_payee, _amount); }
1,760,056
pragma solidity 0.6.12; interface IZeroEx { function getFunctionImplementation(bytes4 _signature) external returns (address); } pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import './IZeroEx.sol'; import '@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol'; import "@0x/contracts-zero-ex/contracts/src/errors/LibProxyRichErrors.sol"; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /// @dev A generic proxy contract which extracts a fee before delegation contract ZeroExProxy is Ownable { using LibBytesV06 for bytes; using SafeERC20 for IERC20; using SafeMath for uint256; address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private constant NULL_ADDRESS = 0x0000000000000000000000000000000000000000; uint256 private constant MAX_UINT = 2**256 - 1; address payable public beneficiary; IZeroEx public zeroEx; mapping(bytes4 => address) implementationOverrides; event BeneficiaryChanged(address newBeneficiary); event ImplementationOverrideSet(bytes4 signature, address implementation); /// @dev Construct this contract and specify a fee beneficiary constructor(IZeroEx _zeroEx, address payable _beneficiary) public { zeroEx = _zeroEx; beneficiary = _beneficiary; } function setZeroEx(IZeroEx _new_zero_ex) public onlyOwner{ zeroEx = _new_zero_ex; } function setBeneficiary(address payable _beneficiary) public onlyOwner { beneficiary = _beneficiary; emit BeneficiaryChanged(_beneficiary); } function setImplementationOverride(bytes4 _signature, address _implementation) public onlyOwner { implementationOverrides[_signature] = _implementation; emit ImplementationOverrideSet(_signature, _implementation); } /// @dev Delegates calls to the specified implementation contract and extracts a fee based on provided arguments /// @param _msgData The byte data representing a swap using the original ZeroEx contract. This is either recieved from the 0x API directly or we construct it in order to perform a Uniswap trade /// @param _feeToken The ERC20 we wish to extract a user fee from. If this is ETH it should be the standard 0xeee ETH address /// @param _fee Fee amount collected and sent to the beneficiary function optimalSwap(bytes calldata _msgData, address _feeToken, uint256 _fee) external payable returns (bytes memory) { payFees(_feeToken, _fee); bytes4 _signature = _msgData.readBytes4(0); address _target = getFunctionImplementation(_signature); if (_target == address(0)) { _revertWithData(LibProxyRichErrors.NotImplementedError(_signature)); } (bool _success, bytes memory _resultData) = _target.delegatecall(_msgData); if (!_success) { _revertWithData(_resultData); } _returnWithData(_resultData); } /// @dev Forwards calls to the zeroEx contract and extracts a fee based on provided arguments /// @param _msgData The byte data representing a swap using the original ZeroEx contract. This is either recieved from the 0x API directly or we construct it in order to perform a Uniswap trade /// @param _feeToken The ERC20 we wish to extract a user fee from. If this is ETH it should be the standard 0xeee ETH address /// @param _inputToken The ERC20 the user is selling. If this is ETH it should be the standard 0xeee ETH address /// @param _inputAmount The amount of _inputToken being sold /// @param _outputToken The ERC20 the user is buying. If this is ETH it should be the standard 0xeee ETH address /// @param _fee Fee amount collected and sent to the beneficiary function proxiedSwap(address _allowanceTarget, bytes calldata _msgData, address _feeToken, address _inputToken, uint256 _inputAmount, address _outputToken, uint256 _fee) external payable returns (bytes memory) { payFees(_feeToken, _fee); uint256 _value = 0; if (_inputToken == ETH_ADDRESS) { _value = msg.value.sub(_fee); } else { _sendERC20(IERC20(_inputToken), msg.sender, address(this), _inputAmount); if (IERC20(_inputToken).allowance(address(this), _allowanceTarget) == 0) { IERC20(_inputToken).safeApprove(_allowanceTarget, MAX_UINT); } } (bool _success, bytes memory _resultData) = address(zeroEx).call{value: _value}(_msgData); if (!_success) { _revertWithData(_resultData); } if (_outputToken == ETH_ADDRESS) { if (address(this).balance>0) { _sendETH(msg.sender, address(this).balance); } else { _revertWithData(_resultData); } } else { uint256 _tokenBalance = IERC20(_outputToken).balanceOf(address(this)); if (_tokenBalance > 0) { IERC20(_outputToken).safeTransfer(msg.sender, _tokenBalance); } else { _revertWithData(_resultData); } } _returnWithData(_resultData); } function getFunctionImplementation(bytes4 _signature) public returns (address _impl) { _impl = implementationOverrides[_signature]; if (_impl == NULL_ADDRESS) { _impl = zeroEx.getFunctionImplementation(_signature); } } /// @dev Fallback for just receiving ether. receive() external payable {} function payFees(address _token, uint256 _amount) private { if (_token == ETH_ADDRESS) { return _sendETH(beneficiary, _amount); } return _sendERC20(IERC20(_token), msg.sender, beneficiary, _amount); } function _sendETH(address payable _toAddress, uint256 _amount) private { if (_amount > 0) { (bool _success,) = _toAddress.call{ value: _amount }(""); require(_success, "Unable to send ETH"); } } function _sendERC20(IERC20 _token, address _fromAddress, address _toAddress, uint256 _amount) private { if (_amount > 0) { _token.safeTransferFrom(_fromAddress, _toAddress, _amount); } } /// @dev Revert with arbitrary bytes. /// @param data Revert data. function _revertWithData(bytes memory data) private pure { assembly { revert(add(data, 32), mload(data)) } } /// @dev Return with arbitrary bytes. /// @param data Return data. function _returnWithData(bytes memory data) private pure { assembly { return(add(data, 32), mload(data)) } } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./errors/LibBytesRichErrorsV06.sol"; import "./errors/LibRichErrorsV06.sol"; library LibBytesV06 { using LibBytesV06 for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// When `from == 0`, the original array will match the slice. /// In other cases its state will be corrupted. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibBytesRichErrorsV06 { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibRichErrorsV06 { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError(string memory message) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibProxyRichErrors { // solhint-disable func-name-mixedcase function NotImplementedError(bytes4 selector) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("NotImplementedError(bytes4)")), selector ); } function InvalidBootstrapCallerError(address actual, address expected) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidBootstrapCallerError(address,address)")), actual, expected ); } function InvalidDieCallerError(address actual, address expected) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidDieCallerError(address,address)")), actual, expected ); } function BootstrapCallFailedError(address target, bytes memory resultData) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("BootstrapCallFailedError(address,bytes)")), target, resultData ); } } // 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; 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: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @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); } } } }
Forwards calls to the zeroEx contract and extracts a fee based on provided arguments _msgData The byte data representing a swap using the original ZeroEx contract. This is either recieved from the 0x API directly or we construct it in order to perform a Uniswap trade _feeToken The ERC20 we wish to extract a user fee from. If this is ETH it should be the standard 0xeee ETH address _inputToken The ERC20 the user is selling. If this is ETH it should be the standard 0xeee ETH address _inputAmount The amount of _inputToken being sold _outputToken The ERC20 the user is buying. If this is ETH it should be the standard 0xeee ETH address _fee Fee amount collected and sent to the beneficiary
function proxiedSwap(address _allowanceTarget, bytes calldata _msgData, address _feeToken, address _inputToken, uint256 _inputAmount, address _outputToken, uint256 _fee) external payable returns (bytes memory) { payFees(_feeToken, _fee); uint256 _value = 0; if (_inputToken == ETH_ADDRESS) { _value = msg.value.sub(_fee); _sendERC20(IERC20(_inputToken), msg.sender, address(this), _inputAmount); if (IERC20(_inputToken).allowance(address(this), _allowanceTarget) == 0) { IERC20(_inputToken).safeApprove(_allowanceTarget, MAX_UINT); } } if (!_success) { _revertWithData(_resultData); } if (_outputToken == ETH_ADDRESS) { if (address(this).balance>0) { _sendETH(msg.sender, address(this).balance); _revertWithData(_resultData); } uint256 _tokenBalance = IERC20(_outputToken).balanceOf(address(this)); if (_tokenBalance > 0) { IERC20(_outputToken).safeTransfer(msg.sender, _tokenBalance); _revertWithData(_resultData); } } _returnWithData(_resultData); }
11,829,930
./partial_match/3/0xa51190143d4e9bcB0495b7443Ec50520ac3CFA97/sources/PLMT3.sol
------------------------------------------------------------------------ Don't accept ETH ------------------------------------------------------------------------
function () public payable { revert(); }
5,337,963
// SPDX-License-Identifier: MIT /* solhint-disable max-states-count*/ pragma solidity 0.6.12; import "./ActiveBridgeSetInterface.sol"; import "./BlockRelayInterface.sol"; /** * @title Active Bridge Set Block relay contract * @notice Contract to store/read block headers from the Witnet network, implements BFT Finality bsaed on the Active Bridge Set (ABS) * @dev More information can be found here https://github.com/witnet/research/blob/master/bridge/docs/BFT_finality.md * DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks * @author Witnet Foundation */ contract ActiveBridgeSetBlockRelay is BlockRelayInterface { struct MerkleRoots { // Hash of the merkle root of the DRs in Witnet uint256 drHashMerkleRoot; // Hash of the merkle root of the tallies in Witnet uint256 tallyHashMerkleRoot; // Hash of the vote that this block extends uint256 previousVote; // Address of the relayer address relayerAddress; } struct Beacon { // Hash of the last block uint256 blockHash; // Epoch of the last block uint256 epoch; } // Struct with the hashes of a votation struct Hashes { uint256 blockHash; uint256 drMerkleRoot; uint256 tallyMerkleRoot; uint256 previousVote; uint256 epoch; } struct VoteInfo { // Information of a Block Candidate uint256 numberOfVotes; Hashes voteHashes; } // Array with the votes for the proposed blocks uint256[] public candidates; // Array with the members of the ABS that have proposed a block address[] public absProposingMembers; // Initializes the block with the maximum number of votes uint256 public winnerVote; uint256 public winnerId; uint256 public winnerDrMerkleRoot; uint256 public winnerTallyMerkleRoot; uint256 public winnerEpoch; // Needed for the constructor uint256 public witnetGenesis; uint256 public epochSeconds; uint256 public firstBlock; // Initializes the current epoch and the epoch in which it is valid to propose blocks uint256 public currentEpoch; uint256 public proposalEpoch; // Initializes the active identities in the ABS uint256 public activeIdentities; // Witnet address address public witnet; ActiveBridgeSetInterface internal wbi; // Last block reported Beacon public lastBlock; // Map a vote proposed to the number of votes received and its hashes mapping(uint256=> VoteInfo) internal voteInfo; // Map the hash of the block to the merkle roots and the previousVote it extends mapping (uint256 => MerkleRoots) public blocks; // Map an epoch to the finalized blockHash mapping(uint256 => uint256) internal epochFinalizedBlock; // Map an address to the epoch when proposing a block mapping(address => uint256) internal addressEpoch; // Ensure block exists modifier blockExists(uint256 _id){ require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block"); _; } // Ensure block does not exist modifier blockDoesNotExist(uint256 _id){ require(blocks[_id].drHashMerkleRoot==0, "The block already existed"); _; } // Ensure that neither Poi nor PoE are allowed if the epoch is pending modifier epochIsFinalized(uint256 _epoch){ require( (epochFinalizedBlock[_epoch] != 0), "The block has not been finalized"); _; } // Ensure that the msg.sender is in the abs modifier isAbsMember(address _address){ require(wbi.absIsMember(_address) == true, "Not a member of the abs"); _; } // Only the owner should be able to push blocks modifier isOwner() { require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts. _; // Otherwise, it continues. } // Ensure the epoch for which the block is been proposed is valid // Valid if it is one epoch before the current epoch modifier epochValid(uint256 _epoch){ currentEpoch = updateEpoch(); if (proposalEpoch == 0) { proposalEpoch = currentEpoch; } require(currentEpoch - 1 == _epoch, "Proposing a block for a non valid epoch"); _; } constructor( uint256 _witnetGenesis, uint256 _epochSeconds, uint256 _firstBlock, address _wbiAddress) public{ // Set the first epoch in Witnet plus the epoch duration when deploying the contract witnetGenesis = _witnetGenesis; epochSeconds = _epochSeconds; firstBlock = _firstBlock; wbi = ActiveBridgeSetInterface(_wbiAddress); witnet = msg.sender; } /// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header /// @return Requests-only merkle root hash in the block header. function readDrMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].drHashMerkleRoot; } /// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header. /// @return tallies-only merkle root hash in the block header. function readTallyMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].tallyHashMerkleRoot; } /// @dev Verifies if the contract is upgradable. /// @return true if the contract upgradable. function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Read the beacon of the last block inserted /// @return bytes to be signed by bridge nodes function getLastBeacon() external view override returns(bytes memory) { return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch); } /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view override returns(uint256) { return lastBlock.epoch; } /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view override returns(uint256) { return lastBlock.blockHash; } /// @dev Verifies the validity of a PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) epochIsFinalized(currentEpoch) returns(bool) { uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot; return(verifyPoi( _poi, drMerkleRoot, _index, _element)); } /// @dev Verifies the validity of a PoI against the tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the element /// @return true or false depending the validity function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot; return(verifyPoi( _poi, tallyMerkleRoot, _index, _element)); } /// @dev Retrieve address of the relayer that relayed a specific block header. /// @param _blockHash Hash of the block header. /// @return address of the relayer. function readRelayerAddress(uint256 _blockHash) external view override blockExists(_blockHash) returns(address) { return blocks[_blockHash].relayerAddress; } /// @dev Proposes a block into the block relay /// @param _blockHash Hash of the block header /// @param _epoch Epoch for which the block is proposed /// @param _drMerkleRoot Merkle root belonging to the data requests /// @param _tallyMerkleRoot Merkle root belonging to the tallies /// @param _previousVote Hash of block's hashes proposed in a previous epoch function proposeBlock( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot, uint256 _previousVote ) external epochValid(_epoch) isAbsMember(msg.sender) blockDoesNotExist(_blockHash) returns(bytes32) { // Check if a msg.sender has already proposed for this epoch require(addressEpoch[msg.sender] < _epoch, "Already proposed a block"); if (addressEpoch[msg.sender] == 0) { absProposingMembers.push(msg.sender); } addressEpoch[msg.sender] = _epoch; // If the porposal epoch chancges try to post the block with more votes if (currentEpoch > proposalEpoch) { // If consensus is achieved, call postNewBlock if (3 * voteInfo[winnerVote].numberOfVotes >= 2 * activeIdentities) { // If it has achieved consensus, post the block postNewBlock( winnerVote, winnerId, winnerEpoch, winnerDrMerkleRoot, winnerTallyMerkleRoot, voteInfo[winnerVote].voteHashes.previousVote); } // Set the winner values to 0 winnerVote = 0; winnerId = 0; winnerEpoch = 0; winnerDrMerkleRoot = 0; winnerTallyMerkleRoot = 0; // Update the proposal epoch proposalEpoch = currentEpoch; } // Hash of the elements of the vote uint256 vote = uint256( sha256( abi.encodePacked( _blockHash, _epoch, _drMerkleRoot, _tallyMerkleRoot, _previousVote))); if (voteInfo[vote].numberOfVotes == 0) { // Add the vote to candidates candidates.push(vote); // Mapping the vote into its hashes voteInfo[vote].voteHashes.blockHash = _blockHash; voteInfo[vote].voteHashes.drMerkleRoot = _drMerkleRoot; voteInfo[vote].voteHashes.tallyMerkleRoot = _tallyMerkleRoot; voteInfo[vote].voteHashes.previousVote = _previousVote; voteInfo[vote].voteHashes.epoch = _epoch; } // Sum one vote voteInfo[vote].numberOfVotes += 1; // If needed, update the block that has more votes if (vote != winnerVote) { // Set as new winner if it has more votes if (voteInfo[vote].numberOfVotes > voteInfo[winnerVote].numberOfVotes) { winnerVote = vote; winnerId = _blockHash; winnerEpoch = _epoch; winnerDrMerkleRoot = _drMerkleRoot; winnerTallyMerkleRoot = _tallyMerkleRoot; } } return bytes32(vote); } /// @dev Updates the epoch function updateEpoch() public view virtual returns(uint256) { // solhint-disable-next-line not-rely-on-time return (block.timestamp - witnetGenesis)/epochSeconds; } /// @dev Post new block into the block relay /// @param _vote Vote created when the block was proposed /// @param _blockHash Hash of the block headerPost /// @param _epoch Witnet epoch to which the block belongs to /// @param _drMerkleRoot Merkle root belonging to the data requests /// @param _tallyMerkleRoot Merkle root belonging to the tallies /// @param _previousVote Hash of block's hashes proposed in the previous epoch function postNewBlock( uint256 _vote, uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot, uint256 _previousVote) private blockDoesNotExist(_blockHash) { // Map the epoch to the vote's Hashes epochFinalizedBlock[_epoch] = voteInfo[_vote].voteHashes.blockHash; blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot; blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot; blocks[_blockHash].relayerAddress = msg.sender; blocks[_blockHash].previousVote = _previousVote; // Select previous vote and corresponding epoch and blockHash uint256 previousVote = blocks[epochFinalizedBlock[_epoch]].previousVote; uint256 epoch = voteInfo[_previousVote].voteHashes.epoch; uint256 previousBlockHash = voteInfo[previousVote].voteHashes.blockHash; uint256 lastEpoch = lastBlock.epoch; // Finalize the previous votes when the corresponding epochs are bigger than the last finalized epoch while (epoch > lastEpoch) { epochFinalizedBlock[epoch] = previousBlockHash; // Map the block hash to its hashes blocks[previousBlockHash].drHashMerkleRoot = voteInfo[previousVote].voteHashes.drMerkleRoot; blocks[previousBlockHash].tallyHashMerkleRoot = voteInfo[previousVote].voteHashes.tallyMerkleRoot; blocks[previousBlockHash].previousVote = voteInfo[previousVote].voteHashes.previousVote; // Update previousVote, epoch and previousBlockHash previousVote = voteInfo[previousVote].voteHashes.previousVote; epoch = voteInfo[previousVote].voteHashes.epoch; previousBlockHash = voteInfo[previousVote].voteHashes.blockHash; } // Assert the concatenation of blocks ends in the right epoch with the right blockHash assert(epoch == lastBlock.epoch && previousBlockHash == lastBlock.blockHash); // Post the last block lastBlock.blockHash = _blockHash; lastBlock.epoch = _epoch; uint256 candidatesLength = candidates.length; // Delete the condidates array so its empty for next epoch for (uint i = 0; i < candidatesLength; i++) { delete voteInfo[candidates[i]].voteHashes; } delete candidates; // Redefine the blockHash and the epoch so it is not deleted when finalized voteInfo[_vote].voteHashes.blockHash = _blockHash; voteInfo[_vote].voteHashes.epoch = _epoch; uint256 proposingMembersLength = absProposingMembers.length; // Delete the ABS members from the list of proposing members for (uint i = 0; i < proposingMembersLength; i++) { delete addressEpoch[absProposingMembers[i]]; } delete absProposingMembers; // Update the ABS activity once finalized activeIdentities = wbi.absCount(); } /// @dev Verifies the validity of a PoI /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _root the merkle root /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyPoi( uint256[] memory _poi, uint256 _root, uint256 _index, uint256 _element) private pure returns(bool) { uint256 tree = _element; uint256 index = _index; // We want to prove that the hash of the _poi and the _element is equal to _root // For knowing if concatenate to the left or the right we check the parity of the the index for (uint i = 0; i < _poi.length; i++) { if (index%2 == 0) { tree = uint256(sha256(abi.encodePacked(tree, _poi[i]))); } else { tree = uint256(sha256(abi.encodePacked(_poi[i], tree))); } index = index >> 1; } return _root == tree; } }
Verifies the validity of a PoI against the tally merkle root _poi the proof of inclusion as [sibling1, sibling2,..] _blockHash the blockHash _index the index in the merkle tree of the element to verify _element the element return true or false depending the validity
function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot; return(verifyPoi( _poi, tallyMerkleRoot, _index, _element)); }
12,760,088
pragma solidity 0.5.8; import './OnlineMarket.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import 'openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; /* * @title StoreFront * * @dev This contract allows storeowners to manage their stores, add/remove products from store and buyers to buy the products * */ contract StoreFront is Ownable, Pausable{ //OnlineMarket Instance OnlineMarket public onlineMarketInstance; /** @dev Constructor to link the Marketplace contract * @param onlineMarketContractAddress to link OnlineMarket contract */ constructor(address onlineMarketContractAddress) public { onlineMarketInstance = OnlineMarket(onlineMarketContractAddress); } /** @dev Struct that hold Stores data * @param storeId Store Id * @param storeName Store name * @param storeOwner address of the storeOwner * @param balance Store balance */ struct Store { bytes32 storeId; string storeName; address storeOwner; uint balance; } /** @dev Struct that hold Products data * @param productId ProductId * @param productName Product name * @param description description of the Product * @param price price of the Product * @param quantity quantity of the product in a store * @param storeId Store Id */ struct Product { bytes32 productId; string productName; string description; uint price; uint quantity; bytes32 storeId; } // Hold all the stores bytes32[] private stores; // Hold mapping of the stores with index mapping(bytes32 => uint) private storesIndex; // Mapping Stores with StoreId mapping(bytes32 => Store) private storeById; // Mapping Store Owners with StoreIds mapping(address => bytes32[]) private storesByOwners; // Mapping Products by Products Id mapping(bytes32 => Product) private productsById; //Mapping of Product by Store mapping(bytes32 => bytes32[]) private productsByStore; //Events which are emitted at various points event LogStoreCreated(bytes32 storeId); event LogStoreRemoved(bytes32 storeId); event LogProductAdded(bytes32 productId); event LogProductRemoved (bytes32 productId,bytes32 storefrontId); event LogBalanceWithdrawn(bytes32 storeId, uint storeBalance); event LogPriceUpdated (bytes32 productId,uint oldPrice,uint newPrice); event LogProductSold(bytes32 productId, bytes32 storeId, uint price, uint buyerQty, uint amount, address buyer, uint remainingQuantity); // Modifier to to restrict function calls to only approved store owner modifier onlyApprovedStoreOwner() { require(onlineMarketInstance.checkStoreOwnerStatus(msg.sender) == true); _; } // Modifier to to restrict function calls to the store owner who created the store modifier onlyStoreOwner(bytes32 storeId) { require(storeById[storeId].storeOwner == msg.sender); _; } /** @dev Function is to create the store by approved store owner * @param storeName Name of the store * @return storeId */ function createStore(string memory storeName) public onlyApprovedStoreOwner whenNotPaused returns(bytes32){ bytes32 storeId = keccak256(abi.encodePacked(msg.sender, storeName, now)); Store memory store = Store(storeId, storeName, msg.sender, 0); storeById[storeId] = store; storesByOwners[msg.sender].push(store.storeId); stores.push(store.storeId); storesIndex[store.storeId] = stores.length-1; emit LogStoreCreated(store.storeId); return store.storeId; } /** @dev Function is to get all the stores * @param storeOwner address * @return storeIds - all the storeIds */ function getStores(address storeOwner) public view onlyApprovedStoreOwner returns(bytes32[] memory){ return storesByOwners[storeOwner]; } /** @dev Function is to get storeId by the store owner * @param storeOwner address * @param index Store owner index * @return storeId */ function getStoreIdByOwner(address storeOwner, uint index) public view returns(bytes32) { return storesByOwners[storeOwner][index]; } /** @dev Function is to get stores count by the store owner * @param storeOwner address * @return no of stores */ function getStoreCountByOwner(address storeOwner) public view returns(uint){ return storesByOwners[storeOwner].length; } /** @dev Function is to remove a store * @param storeId Id of the store */ function removeStore(bytes32 storeId) public onlyApprovedStoreOwner onlyStoreOwner(storeId) whenNotPaused { //Remove all products in the store; removeProducts(storeId); //remove store from stores array uint storeIndex = storesIndex[storeId]; if (stores.length > 1) { stores[storeIndex] = stores[stores.length-1]; } stores.length--; //remove store by Owner uint length = storesByOwners[msg.sender].length; for (uint i=0; i<length; i++) { if(storesByOwners[msg.sender][i] == storeId){ if(i!=length-1){ storesByOwners[msg.sender][i] = storesByOwners[msg.sender][length-1]; } delete storesByOwners[msg.sender][length-1]; storesByOwners[msg.sender].length--; break; } } // Withdraw store balance and transfer to msg.sender uint storeBalance = storeById[storeId].balance; if (storeBalance > 0) { msg.sender.transfer(storeBalance); storeById[storeId].balance = 0; emit LogBalanceWithdrawn(storeId, storeBalance); } //Delete Store By Id delete storeById[storeId]; emit LogStoreRemoved(storeId); } /** @dev Function is to withdraw the store balance * @param storeId Id of the store */ function withdrawStoreBalance(bytes32 storeId) public payable onlyApprovedStoreOwner onlyStoreOwner(storeId) whenNotPaused{ require(storeById[storeId].balance > 0); uint storeBalance = storeById[storeId].balance; msg.sender.transfer(storeBalance); emit LogBalanceWithdrawn(storeId, storeBalance); storeById[storeId].balance = 0; } /** @dev Function is to get stores Id * @param index storeId index * @return storeId */ function getStoreId(uint index) public view returns(bytes32){ return stores[index]; } /** @dev Function is to get store owner of the store * @param storeId Id of the store * @return storeOwner address */ function getStoreOwner(bytes32 storeId) public view returns(address){ return storeById[storeId].storeOwner; } /** @dev Function is to get store name * @param storeId Id of the store * @return storeName */ function getStoreName(bytes32 storeId) public view returns(string memory){ return storeById[storeId].storeName; } /** @dev Function is to get total store counts * @return totalStoreCount */ function getTotalStoresCount() view public returns (uint) { return stores.length; } /** @dev Function is to get store balance * @param storeId Id of the store * @return storeBalance */ function getStoreBalance(bytes32 storeId) public view onlyApprovedStoreOwner onlyStoreOwner(storeId) returns (uint) { return storeById[storeId].balance; } /** @dev Function is to add a Product to the store * @param storeId Id of the store * @param productName Name of the product * @param description Description of the product * @param price price of the product * @param quantity quantity of the product * @return productId */ function addProduct(bytes32 storeId, string memory productName, string memory description, uint price, uint quantity) public onlyApprovedStoreOwner onlyStoreOwner(storeId) whenNotPaused returns(bytes32){ bytes32 productId = keccak256(abi.encodePacked(storeId, productName, now)); Product memory product = Product(productId, productName, description, price, quantity, storeId); productsById[productId] = product; productsByStore[storeId].push(product.productId); emit LogProductAdded(product.productId); return product.productId; } /** @dev Function is to update Product price of a store * @param storeId Id of the store * @param productId Id of the product * @param newPrice new price of the product */ function updateProductPrice(bytes32 storeId, bytes32 productId, uint newPrice) public onlyStoreOwner(storeId) whenNotPaused { Product storage product = productsById[productId]; uint oldPrice = product.price; productsById[productId].price = newPrice; emit LogPriceUpdated(productId, oldPrice, newPrice); } /** @dev Function is to get the price of the Product * @param productId Id of the product * @return price of the product */ function getProductPrice(bytes32 productId) public view returns (uint) { return productsById[productId].price; } /** @dev Function is to get the name of the Product * @param productId Id of the product * @return name of the product */ function getProductName(bytes32 productId) public view returns (string memory) { return productsById[productId].productName; } /** @dev Function is to get productIds in a store * @param storeId Id of the store * @return productIds in a store */ function getProductIdsByStore(bytes32 storeId) public view returns(bytes32[] memory){ return productsByStore[storeId]; } /** @dev Function is to get productId in a store * @param storeId Id of the store * @param index product Id index in a store * @return productId in a store */ function getProductIdByStore(bytes32 storeId, uint index) public view returns(bytes32){ return productsByStore[storeId][index]; } /** @dev Function is to get no of products in a store * @param storeId Id of the store * @return no of products in a store */ function getProductsCountByStore(bytes32 storeId) public view returns(uint){ return productsByStore[storeId].length; } /** @dev Function is to get product by Id * @param productId Id of the product * @return productId Id of the product * @return productName Name of the product * @return description Description of the product * @return price price of the product * @return quantity quantity of the product * @return storeId Id of the store */ function getProductById(bytes32 productId) public view returns (string memory, string memory, uint, uint, bytes32){ return (productsById[productId].productName, productsById[productId].description, productsById[productId].price, productsById[productId].quantity, productsById[productId].storeId); } /** @dev Function is to remove products in a store. * @param storeId Id of the store */ function removeProducts(bytes32 storeId) public onlyApprovedStoreOwner onlyStoreOwner(storeId) whenNotPaused{ for (uint i=0; i< productsByStore[storeId].length; i++) { bytes32 productId = productsByStore[storeId][i]; delete productsByStore[storeId][i]; delete productsById[productId]; } } /** @dev Function is to remove product in a store. * @param storeId Id of the store * @param productId Id of the Product */ function removeProductByStore(bytes32 storeId, bytes32 productId) public onlyApprovedStoreOwner onlyStoreOwner(storeId) whenNotPaused{ bytes32[] memory productIds = productsByStore[storeId]; uint productsCount = productIds.length; for(uint i=0; i<productsCount; i++) { if (productIds[i] == productId) { productIds[i] = productIds[productsCount-1]; delete productIds[productsCount-1]; productsByStore[storeId] = productIds; delete productsById[productId]; emit LogProductRemoved(productId, storeId); break; } } } /** @dev Function is to buy the products by the buyer * @param storeId Id of the store * @param productId Id of the Product * @param quantity quanities of the product to buy * @return true if product is bought otherwise false */ function buyProduct(bytes32 storeId, bytes32 productId, uint quantity) public payable whenNotPaused returns(bool){ //store owner can not buy its own productsById Product storage prdct = productsById[productId]; Store storage str = storeById[storeId]; //store owner can not buy its own products require(str.storeOwner != msg.sender); uint amount = prdct.price*quantity; require(msg.value >= amount); require (quantity <= prdct.quantity); //refund remaining fund back to buyer uint remainingValue = msg.value-amount; msg.sender.transfer(remainingValue); //update product quantity & store balance prdct.quantity-=quantity; str.balance+=amount; emit LogProductSold(productId, storeId, prdct.price, quantity, amount, msg.sender, prdct.quantity); return true; } }
Function is to withdraw the store balance storeId Id of the store/
function withdrawStoreBalance(bytes32 storeId) public payable onlyApprovedStoreOwner onlyStoreOwner(storeId) whenNotPaused{ require(storeById[storeId].balance > 0); uint storeBalance = storeById[storeId].balance; msg.sender.transfer(storeBalance); emit LogBalanceWithdrawn(storeId, storeBalance); storeById[storeId].balance = 0; }
5,373,212
pragma solidity ^0.4.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); 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; } } /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLibExt { function times(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function divides(uint a, uint b) returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function minus(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a); return c; } } contract Destructable is Ownable { function burn() public onlyOwner { selfdestruct(owner); } } contract TokensContract { function balanceOf(address who) public constant returns (uint256); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); } contract Insurance is Destructable, SafeMath { uint startClaimDate; uint endClaimDate; uint rewardWeiCoefficient; uint256 buyPrice; address tokensContractAddress; uint256 ichnDecimals; mapping (address => uint256) buyersBalances; struct ClientInsurance { uint256 tokensCount; bool isApplied; bool exists; bool isBlocked; } mapping(address => ClientInsurance) insurancesMap; function Insurance() public { /* I-CHAIN.NET (ICHN) ERC20 token */ tokensContractAddress = 0x3ab7b695573017eeBD6377c433F9Cf3eF5B4cd48; /* UTC, 31 dec 2020 00:00 - 2 feb 2021 00:00 */ startClaimDate = 1609372800; endClaimDate = 1612224000; /* 0.1 ether */ rewardWeiCoefficient = 100000000000000000; /* 0.05 ether */ buyPrice = 50000000000000000; /* ICHN Token Decimals is 18 */ ichnDecimals = 1000000000000000000; } /** * Don't expect to just send money by anyone except the owner */ function () public payable { throw; } /** * Owner can add ETH to contract */ function addEth() public payable onlyOwner { } /** * Owner can transfer ETH from contract to address * Amount - 18 decimals */ function transferEthTo(address to, uint256 amount) public payable onlyOwner { require(address(this).balance > amount); to.transfer(amount); } /** * Basic entry point for buy insurance */ function buy() public payable { /* Can be called only once for address */ require(buyersBalances[msg.sender] == 0); /* Checking price */ require(msg.value == buyPrice); /* At least one token */ require(hasTokens(msg.sender)); /* Remember payment */ buyersBalances[msg.sender] = safeAdd(buyersBalances[msg.sender], msg.value); } function isClient(address clientAddress) public constant onlyOwner returns(bool) { return insurancesMap[clientAddress].exists; } function addBuyer(address clientAddress, uint256 tokensCount) public onlyOwner { require( (clientAddress != address(0)) && (tokensCount > 0) ); /* Checking payment */ require(buyersBalances[clientAddress] == buyPrice); /* Can be called only once for address */ require(!insurancesMap[clientAddress].exists); /* Checking the current number of tokens */ require(getTokensCount(clientAddress) >= tokensCount); insurancesMap[clientAddress] = ClientInsurance(tokensCount, false, true, false); } function claim(address to, uint256 returnedTokensCount) public onlyOwner { /* Can be called only on time range */ require(now > startClaimDate && now < endClaimDate); /* Can be called once for address */ require( (to != address(0)) && (insurancesMap[to].exists) && (!insurancesMap[to].isApplied) && (!insurancesMap[to].isBlocked) ); /* Tokens returned */ require(returnedTokensCount >= insurancesMap[to].tokensCount); /* Start transfer */ uint amount = getRewardWei(to); require(address(this).balance > amount); insurancesMap[to].isApplied = true; to.transfer(amount); } function blockClient(address clientAddress) public onlyOwner { insurancesMap[clientAddress].isBlocked = true; } function unblockClient(address clientAddress) public onlyOwner { insurancesMap[clientAddress].isBlocked = false; } function isClientBlocked(address clientAddress) public constant onlyOwner returns(bool) { return insurancesMap[clientAddress].isBlocked; } /** * Sets buy price for insurance */ function setBuyPrice(uint256 priceWei) public onlyOwner { buyPrice = priceWei; } /** * Sets tokens contract address from which check balance of tokens */ function setTokensContractAddress(address contractAddress) public onlyOwner { tokensContractAddress = contractAddress; } /** * Returns address of tokens contract from which check balance of tokens */ function getTokensContractAddress() public constant onlyOwner returns(address) { return tokensContractAddress; } function getRewardWei(address clientAddress) private constant returns (uint256) { uint tokensCount = insurancesMap[clientAddress].tokensCount; return safeMul(tokensCount, rewardWeiCoefficient); } function hasTokens(address clientAddress) private constant returns (bool) { return getTokensCount(clientAddress) > 0; } function getTokensCount(address clientAddress) private constant returns (uint256) { TokensContract tokensContract = TokensContract(tokensContractAddress); uint256 tcBalance = tokensContract.balanceOf(clientAddress); return safeDiv(tcBalance, ichnDecimals); } /** * Transfer ERC20 tokens from contract to address * tokensAmount - 18 decimals */ function transferTokensTo(address to, uint256 tokensAmount) public onlyOwner { TokensContract tokensContract = TokensContract(tokensContractAddress); tokensContract.approve(address(this), tokensAmount); tokensContract.transferFrom(address(this), to, tokensAmount); } function getStartClaimDate() public constant onlyOwner returns(uint) { return startClaimDate; } function getEndClaimDate() public constant onlyOwner returns(uint) { return endClaimDate; } }
Owner can transfer ETH from contract to address Amount - 18 decimals/
function transferEthTo(address to, uint256 amount) public payable onlyOwner { require(address(this).balance > amount); to.transfer(amount); }
5,377,255
pragma solidity ^0.4.21; library Dna { struct CoreInfo { uint256 dna; uint32 proficiency; uint32 personality; } } contract DnaCore { uint256 private DNA_DIGIT = 35; uint256 private PROFICIENCY_DIGIT = 3; uint256 private PERSONALITY_DIGIT = 6; uint256 internal DNA_LIMIT = 10**DNA_DIGIT; uint256 private DNA_CUTOFF = 10**(PERSONALITY_DIGIT + 1); uint256 private PROFICIENCY_LIMIT = 10**PROFICIENCY_DIGIT; // Talented >> Fast-learner >> Clumsy > Procastinator > None uint256[] internal PROFICIENCY_THRESHOLD = [25, 100, 175, 200, 300]; uint256 private PERSONALITY_LIMIT = 10**PERSONALITY_DIGIT; // Sanguine >> choleric >> melancholic >> phlegmatic uint256[] internal PERSONALITY_THRESHOLD = [150, 200, 300, 350]; function _interpretThreshold(uint32 _val, uint256[] threshold) private pure returns (uint32) { // 5 Proficiency type with *Talented* and *Fats-learner* as 'rare' trait. uint cumulative = 0; for (uint i = 0; i < threshold.length; i++) { uint currThreshold = threshold[i]; if (_val < cumulative + currThreshold) { return uint32(i); } cumulative += currThreshold; } return uint32(threshold.length - 1); } function _interpretPersonality(uint8[] quizzes, uint32 _personality) private view returns (uint32) { // quizes will contribute to each threshold. uint[] memory updatedThreshold = PERSONALITY_THRESHOLD; uint count = 0; for (uint i = 0; i < quizzes.length; i++) { count += quizzes[i]; } uint nudge = 10 * (quizzes.length - 1); if (count > 0 && count < quizzes.length) { // Need to update the threshold by a bit. for (i = 0; i < quizzes.length; i++) { uint denom = quizzes.length * quizzes[i]; denom = denom - count; updatedThreshold[i] += nudge / denom; } } return _interpretThreshold(_personality, updatedThreshold); } function _interpretProficiency(uint8[] quizzes, uint32 _proficiency) private view returns (uint32) { // quizes will contribute to each threshold. uint[] memory updatedThreshold = PROFICIENCY_THRESHOLD; uint count = 0; for (uint i = 0; i < quizzes.length; i++) { count += quizzes[i]; } uint nudge = 10 * (quizzes.length - 1); if (count > 0 && count < quizzes.length) { // Need to update the threshold by a bit. for (i = 0; i < quizzes.length; i++) { uint denom = quizzes.length * quizzes[i]; denom = denom - count; updatedThreshold[i] += nudge / denom; } } return _interpretThreshold(_proficiency, updatedThreshold); } function _generateRandomTraits(uint8[] _quizzes, string _name, address _owner) internal view returns (uint256 dna, uint32 proficiency, uint32 personality){ uint256 traitRandomness = uint(keccak256(now, _owner, _name)); dna = traitRandomness % DNA_LIMIT; if (dna / (10**(DNA_DIGIT - 1)) == 0) { dna += 10**(DNA_DIGIT - 1); } // Interpret each DNA component. proficiency = uint32(dna % PROFICIENCY_LIMIT); personality = uint32(dna % PERSONALITY_LIMIT / (PERSONALITY_LIMIT / PROFICIENCY_LIMIT)); proficiency = _interpretThreshold(proficiency, PROFICIENCY_THRESHOLD); personality = _interpretPersonality(_quizzes, personality); dna = dna / DNA_CUTOFF; } function _combineDna(uint256 _dna, uint256 _otherDna, uint256 _randomness, uint256 _threshold) internal view returns (uint256) { uint256 newDna = 0; uint256 randomDna = uint256((_randomness / DNA_LIMIT) % DNA_LIMIT); if (randomDna / (10**(DNA_DIGIT - 1)) == 0) { randomDna += 10**(DNA_DIGIT - 1); } uint256 thresholdCheck = uint256(_randomness % (DNA_LIMIT * 10) / DNA_LIMIT); if (thresholdCheck < _threshold) { // :( Dna is now just random. return randomDna; } // Now, here's where things get interesting... // The combined DNA has a change of 40% to get trait from each parent and 10% random PER DIGIT. // Let's do this one-by-one. uint256 curr; uint256 digit; for (uint256 i = 0; i < DNA_DIGIT; i++) { curr = _randomness % 10; _randomness = _randomness / 10; // TODO: should we make this value adjustable? if (curr < 4) { digit = (_dna / 10**i) % 10; } else if (curr < 8) { digit = (_otherDna / 10**i) % 10; } else { digit = (randomDna / 10**i) % 10; } newDna += digit * (10 ** i); } return newDna; } function _combineTwoTraits(uint256[3] info, uint256[3] otherInfo, string _name, address _owner, uint256 _threshold) internal view returns (uint256 newDna, uint32 newProficiency, uint32 newPersonality) { // TODO uint256 ownerRandomness = uint(keccak256(now, _owner, _name)); newDna = _combineDna(info[0], otherInfo[0], ownerRandomness, _threshold); uint8[] memory personalityQuizzes = new uint8[](PERSONALITY_THRESHOLD.length); personalityQuizzes[info[2]] = 1; personalityQuizzes[otherInfo[2]] = 1; newProficiency = uint32(ownerRandomness % PROFICIENCY_LIMIT); newPersonality = uint32(ownerRandomness % PERSONALITY_LIMIT / (PERSONALITY_LIMIT / PROFICIENCY_LIMIT)); uint8[] memory proficiencyQuizzes = new uint8[](PROFICIENCY_THRESHOLD.length); proficiencyQuizzes[info[1]] = 1; proficiencyQuizzes[otherInfo[1]] = 1; newPersonality = _interpretPersonality(personalityQuizzes, newPersonality); newProficiency = _interpretProficiency(proficiencyQuizzes, newProficiency); } uint256 LEVEL_THRESHOLD = 75; function _randomLevel(uint256 _maxLevel, address _owner) internal view returns (uint256) { if (_maxLevel == 1) { return _maxLevel; } uint256 ownerRandomness = uint(keccak256(now, _owner)); uint256 levelRandomness = uint256(ownerRandomness % (DNA_LIMIT * 100) / DNA_LIMIT); // TODO: 3/4 if (levelRandomness <= LEVEL_THRESHOLD) { return _maxLevel; } else if ((levelRandomness - LEVEL_THRESHOLD) * 100 / (100 - LEVEL_THRESHOLD) <= LEVEL_THRESHOLD) { return (_maxLevel - 1); } else { if (_maxLevel <= 2) { return 1; } else { return (_maxLevel - 2); } } } }
:( Dna is now just random. TODO: should we make this value adjustable?
function _combineDna(uint256 _dna, uint256 _otherDna, uint256 _randomness, uint256 _threshold) internal view returns (uint256) { uint256 newDna = 0; uint256 randomDna = uint256((_randomness / DNA_LIMIT) % DNA_LIMIT); if (randomDna / (10**(DNA_DIGIT - 1)) == 0) { randomDna += 10**(DNA_DIGIT - 1); } uint256 thresholdCheck = uint256(_randomness % (DNA_LIMIT * 10) / DNA_LIMIT); if (thresholdCheck < _threshold) { return randomDna; } uint256 digit; for (uint256 i = 0; i < DNA_DIGIT; i++) { curr = _randomness % 10; _randomness = _randomness / 10; if (curr < 4) { digit = (_dna / 10**i) % 10; digit = (_otherDna / 10**i) % 10; digit = (randomDna / 10**i) % 10; } newDna += digit * (10 ** i); } return newDna; }
5,476,736
pragma solidity 0.5.17; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCDepositToken} from "./TBTCDepositToken.sol"; import {FeeRebateToken} from "./FeeRebateToken.sol"; import {TBTCToken} from "./TBTCToken.sol"; import {TBTCConstants} from "./TBTCConstants.sol"; import "../deposit/Deposit.sol"; import "./TBTCSystemAuthority.sol"; /// @title Vending Machine /// @notice The Vending Machine swaps TDTs (`TBTCDepositToken`) /// to TBTC (`TBTCToken`) and vice versa. /// @dev The Vending Machine should have exclusive TBTC and FRT (`FeeRebateToken`) minting /// privileges. contract VendingMachine is TBTCSystemAuthority{ using SafeMath for uint256; TBTCToken tbtcToken; TBTCDepositToken tbtcDepositToken; FeeRebateToken feeRebateToken; uint256 createdAt; constructor(address _systemAddress) TBTCSystemAuthority(_systemAddress) public { createdAt = block.timestamp; } /// @notice Set external contracts needed by the Vending Machine. /// @dev Addresses are used to update the local contract instance. /// @param _tbtcToken TBTCToken contract. More info in `TBTCToken`. /// @param _tbtcDepositToken TBTCDepositToken (TDT) contract. More info in `TBTCDepositToken`. /// @param _feeRebateToken FeeRebateToken (FRT) contract. More info in `FeeRebateToken`. function setExternalAddresses( TBTCToken _tbtcToken, TBTCDepositToken _tbtcDepositToken, FeeRebateToken _feeRebateToken ) external onlyTbtcSystem { tbtcToken = _tbtcToken; tbtcDepositToken = _tbtcDepositToken; feeRebateToken = _feeRebateToken; } /// @notice Burns TBTC and transfers the tBTC Deposit Token to the caller /// as long as it is qualified. /// @dev We burn the lotSize of the Deposit in order to maintain /// the TBTC supply peg in the Vending Machine. VendingMachine must be approved /// by the caller to burn the required amount. /// @param _tdtId ID of tBTC Deposit Token to buy. function tbtcToTdt(uint256 _tdtId) external { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); uint256 depositValue = Deposit(address(uint160(_tdtId))).lotSizeTbtc(); require(tbtcToken.balanceOf(msg.sender) >= depositValue, "Not enough TBTC for TDT exchange"); tbtcToken.burnFrom(msg.sender, depositValue); // TODO do we need the owner check below? transferFrom can be approved for a user, which might be an interesting use case. require(tbtcDepositToken.ownerOf(_tdtId) == address(this), "Deposit is locked"); tbtcDepositToken.transferFrom(address(this), msg.sender, _tdtId); } /// @notice Transfer the tBTC Deposit Token and mint TBTC. /// @dev Transfers TDT from caller to vending machine, and mints TBTC to caller. /// Vending Machine must be approved to transfer TDT by the caller. /// @param _tdtId ID of tBTC Deposit Token to sell. function tdtToTbtc(uint256 _tdtId) public { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); tbtcDepositToken.transferFrom(msg.sender, address(this), _tdtId); Deposit deposit = Deposit(address(uint160(_tdtId))); uint256 signerFee = deposit.signerFeeTbtc(); uint256 depositValue = deposit.lotSizeTbtc(); require(canMint(depositValue), "Can't mint more than the max supply cap"); // If the backing Deposit does not have a signer fee in escrow, mint it. if(tbtcToken.balanceOf(address(_tdtId)) < signerFee) { tbtcToken.mint(msg.sender, depositValue.sub(signerFee)); tbtcToken.mint(address(_tdtId), signerFee); } else{ tbtcToken.mint(msg.sender, depositValue); } // owner of the TDT during first TBTC mint receives the FRT if(!feeRebateToken.exists(_tdtId)){ feeRebateToken.mint(msg.sender, _tdtId); } } /// @notice Return whether an amount of TBTC can be minted according to the supply cap /// schedule /// @dev This function is also used by TBTCSystem to decide whether to allow a new deposit. /// @return True if the amount can be minted without hitting the max supply, false otherwise. function canMint(uint256 amount) public view returns (bool) { return getMintedSupply().add(amount) < getMaxSupply(); } /// @notice Determines whether a deposit is qualified for minting TBTC. /// @param _depositAddress The address of the deposit function isQualified(address payable _depositAddress) public view returns (bool) { return Deposit(_depositAddress).inActive(); } /// @notice Return the minted TBTC supply in weitoshis (BTC * 10 ** 18). function getMintedSupply() public view returns (uint256) { return tbtcToken.totalSupply(); } /// @notice Get the maximum TBTC token supply based on the age of the /// contract deployment. The supply cap starts at 2 BTC for the two /// days, 100 for the first week, 250 for the next, then 500, 750, /// 1000, 1500, 2000, 2500, and 3000... finally removing the minting /// restriction after 9 weeks and returning 21M BTC as a sanity /// check. /// @return The max supply in weitoshis (BTC * 10 ** 18). function getMaxSupply() public view returns (uint256) { uint256 age = block.timestamp - createdAt; if(age < 2 days) { return 2 * 10 ** 18; } if (age < 7 days) { return 100 * 10 ** 18; } if (age < 14 days) { return 250 * 10 ** 18; } if (age < 21 days) { return 500 * 10 ** 18; } if (age < 28 days) { return 750 * 10 ** 18; } if (age < 35 days) { return 1000 * 10 ** 18; } if (age < 42 days) { return 1500 * 10 ** 18; } if (age < 49 days) { return 2000 * 10 ** 18; } if (age < 56 days) { return 2500 * 10 ** 18; } if (age < 63 days) { return 3000 * 10 ** 18; } return 21e6 * 10 ** 18; } // WRAPPERS /// @notice Qualifies a deposit and mints TBTC. /// @dev User must allow VendingManchine to transfer TDT. function unqualifiedDepositToTbtc( address payable _depositAddress, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters Deposit _d = Deposit(_depositAddress); _d.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); tdtToTbtc(uint256(_depositAddress)); } /// @notice Redeems a Deposit by purchasing a TDT with TBTC for _finalRecipient, /// and using the TDT to redeem corresponding Deposit as _finalRecipient. /// This function will revert if the Deposit is not in ACTIVE state. /// @dev Vending Machine transfers TBTC allowance to Deposit. /// @param _depositAddress The address of the Deposit to redeem. /// @param _outputValueBytes The 8-byte Bitcoin transaction output size in Little Endian. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function tbtcToBtc( address payable _depositAddress, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters require(tbtcDepositToken.exists(uint256(_depositAddress)), "tBTC Deposit Token does not exist"); Deposit _d = Deposit(_depositAddress); tbtcToken.burnFrom(msg.sender, _d.lotSizeTbtc()); tbtcDepositToken.approve(_depositAddress, uint256(_depositAddress)); uint256 tbtcOwed = _d.getOwnerRedemptionTbtcRequirement(msg.sender); if(tbtcOwed != 0){ tbtcToken.transferFrom(msg.sender, address(this), tbtcOwed); tbtcToken.approve(_depositAddress, tbtcOwed); } _d.transferAndRequestRedemption(_outputValueBytes, _redeemerOutputScript, msg.sender); } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity 0.5.17; /** * @title Keep interface */ interface ITBTCSystem { // expected behavior: // return the price of 1 sat in wei // these are the native units of the deposit contract function fetchBitcoinPrice() external view returns (uint256); // passthrough requests for the oracle function fetchRelayCurrentDifficulty() external view returns (uint256); function fetchRelayPreviousDifficulty() external view returns (uint256); function getNewDepositFeeEstimate() external view returns (uint256); function getAllowNewDeposits() external view returns (bool); function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) external view returns (bool); function requestNewKeep(uint64 _requestedLotSizeSatoshis, uint256 _maxSecuredLifetime) external payable returns (address); function getSignerFeeDivisor() external view returns (uint16); function getInitialCollateralizedPercent() external view returns (uint16); function getUndercollateralizedThresholdPercent() external view returns (uint16); function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16); } pragma solidity 0.5.17; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositFunding} from "./DepositFunding.sol"; import {DepositRedemption} from "./DepositRedemption.sol"; import {DepositStates} from "./DepositStates.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; import "../system/DepositFactoryAuthority.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. /// @title tBTC Deposit /// @notice This is the main contract for tBTC. It is the state machine that /// (through various libraries) handles bitcoin funding, bitcoin-spv /// proofs, redemption, liquidation, and fraud logic. /// @dev This contract presents a public API that exposes the following /// libraries: /// /// - `DepositFunding` /// - `DepositLiquidaton` /// - `DepositRedemption`, /// - `DepositStates` /// - `DepositUtils` /// - `OutsourceDepositLogging` /// - `TBTCConstants` /// /// Where these libraries require deposit state, this contract's state /// variable `self` is used. `self` is a struct of type /// `DepositUtils.Deposit` that contains all aspects of the deposit state /// itself. contract Deposit is DepositFactoryAuthority { using DepositRedemption for DepositUtils.Deposit; using DepositFunding for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; DepositUtils.Deposit self; /// @dev Deposit should only be _constructed_ once. New deposits are created /// using the `DepositFactory.createDeposit` method, and are clones of /// the constructed deposit. The factory will set the initial values /// for a new clone using `initializeDeposit`. constructor () public { // The constructed Deposit will never be used, so the deposit factory // address can be anything. Clones are updated as per above. initialize(address(0xdeadbeef)); } /// @notice Deposits do not accept arbitrary ETH. function () external payable { require(msg.data.length == 0, "Deposit contract was called with unknown function selector."); } //----------------------------- METADATA LOOKUP ------------------------------// /// @notice Get this deposit's BTC lot size in satoshis. /// @return uint64 lot size in satoshis. function lotSizeSatoshis() external view returns (uint64){ return self.lotSizeSatoshis; } /// @notice Get this deposit's lot size in TBTC. /// @dev This is the same as lotSizeSatoshis(), but is multiplied to scale /// to 18 decimal places. /// @return uint256 lot size in TBTC precision (max 18 decimal places). function lotSizeTbtc() external view returns (uint256){ return self.lotSizeTbtc(); } /// @notice Get the signer fee for this deposit, in TBTC. /// @dev This is the one-time fee required by the signers to perform the /// tasks needed to maintain a decentralized and trustless model for /// tBTC. It is a percentage of the deposit's lot size. /// @return Fee amount in TBTC. function signerFeeTbtc() external view returns (uint256) { return self.signerFeeTbtc(); } /// @notice Get the integer representing the current state. /// @dev We implement this because contracts don't handle foreign enums /// well. See `DepositStates` for more info on states. /// @return The 0-indexed state from the DepositStates enum. function currentState() external view returns (uint256) { return uint256(self.currentState); } /// @notice Check if the Deposit is in ACTIVE state. /// @return True if state is ACTIVE, false otherwise. function inActive() external view returns (bool) { return self.inActive(); } /// @notice Get the contract address of the BondedECDSAKeep associated with /// this Deposit. /// @dev The keep contract address is saved on Deposit initialization. /// @return Address of the Keep contract. function keepAddress() external view returns (address) { return self.keepAddress; } /// @notice Retrieve the remaining term of the deposit in seconds. /// @dev The value accuracy is not guaranteed since block.timestmap can be /// lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at /// term. function remainingTerm() external view returns(uint256){ return self.remainingTerm(); } /// @notice Get the current collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value the /// signers currently must hold as bond. /// @return The current collateralization level for this deposit. function collateralizationPercentage() external view returns (uint256) { return self.collateralizationPercentage(); } /// @notice Get the initial collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value /// the signers hold initially. It is set at creation time. /// @return The initial collateralization level for this deposit. function initialCollateralizedPercent() external view returns (uint16) { return self.initialCollateralizedPercent; } /// @notice Get the undercollateralization level for this Deposit. /// @dev This collateralization level is semi-critical. If the /// collateralization level falls below this percentage the Deposit can /// be courtesy-called by calling `notifyCourtesyCall`. This value /// represents the percentage of the backing BTC value the signers must /// hold as bond in order to not be undercollateralized. It is set at /// creation time. Note that the value for new deposits in TBTCSystem /// can be changed by governance, but the value for a particular /// deposit is static once the deposit is created. /// @return The undercollateralized level for this deposit. function undercollateralizedThresholdPercent() external view returns (uint16) { return self.undercollateralizedThresholdPercent; } /// @notice Get the severe undercollateralization level for this Deposit. /// @dev This collateralization level is critical. If the collateralization /// level falls below this percentage the Deposit can get liquidated. /// This value represents the percentage of the backing BTC value the /// signers must hold as bond in order to not be severely /// undercollateralized. It is set at creation time. Note that the /// value for new deposits in TBTCSystem can be changed by governance, /// but the value for a particular deposit is static once the deposit /// is created. /// @return The severely undercollateralized level for this deposit. function severelyUndercollateralizedThresholdPercent() external view returns (uint16) { return self.severelyUndercollateralizedThresholdPercent; } /// @notice Get the value of the funding UTXO. /// @dev This call will revert if the deposit is not in a state where the /// UTXO info should be valid. In particular, before funding proof is /// successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), this value /// would not be valid. /// @return The value of the funding UTXO in satoshis. function utxoValue() external view returns (uint256){ require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return self.utxoValue(); } /// @notice Returns information associated with the funding UXTO. /// @dev This call will revert if the deposit is not in a state where the /// funding info should be valid. In particular, before funding proof /// is successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of /// these values are set or valid. /// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint). function fundingInfo() external view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) { require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint); } /// @notice Calculates the amount of value at auction right now. /// @dev This call will revert if the deposit is not in a state where an /// auction is currently in progress. /// @return The value in wei that would be received in exchange for the /// deposit's lot size in TBTC if `purchaseSignerBondsAtAuction` /// were called at the time this function is called. function auctionValue() external view returns (uint256) { require( self.inSignerLiquidation(), "Deposit has no funds currently at auction" ); return self.auctionValue(); } /// @notice Get caller's ETH withdraw allowance. /// @dev Generally ETH is only available to withdraw after the deposit /// reaches a closed state. The amount reported is for the sender, and /// can be withdrawn using `withdrawFunds` if the deposit is in an end /// state. /// @return The withdraw allowance in wei. function withdrawableAmount() external view returns (uint256) { return self.getWithdrawableAmount(); } //------------------------------ FUNDING FLOW --------------------------------// /// @notice Notify the contract that signing group setup has timed out if /// retrieveSignerPubkey is not successfully called within the /// allotted time. /// @dev This is considered a signer fault, and the signers' bonds are used /// to make the deposit setup fee available for withdrawal by the TDT /// holder as a refund. The remainder of the signers' bonds are /// returned to the bonding pool and the signers are released from any /// further responsibilities. Reverts if the deposit is not awaiting /// signer setup or if the signing group formation timeout has not /// elapsed. function notifySignerSetupFailed() external { self.notifySignerSetupFailed(); } /// @notice Notify the contract that the ECDSA keep has generated a public /// key so the deposit contract can pull it in. /// @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a /// RegisteredPubkey event with the two components. Reverts if the /// deposit is not awaiting signer setup, if the generated public key /// is unset or has incorrect length, or if the public key has a 0 /// X or Y value. function retrieveSignerPubkey() external { self.retrieveSignerPubkey(); } /// @notice Notify the contract that the funding phase of the deposit has /// timed out if `provideBTCFundingProof` is not successfully called /// within the allotted time. Any sent BTC is left under control of /// the signer group, and the funder can use `requestFunderAbort` to /// request an at-signer-discretion return of any BTC sent to a /// deposit that has been notified of a funding timeout. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Emits a SetupFailed event. /// Reverts if the funding timeout has not yet elapsed, or if the /// deposit is not currently awaiting funding proof. function notifyFundingTimedOut() external { self.notifyFundingTimedOut(); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests the return of a sent UTXO to _abortOutputScript. It /// imposes no requirements on the signing group. Signers should /// send their UTXO to the requested output script, but do so at /// their discretion and with no penalty for failing to do so. This /// can be used for example when a UTXO is sent that is the wrong /// size for the lot. /// @dev This is a self-admitted funder fault, and is only be callable by /// the TDT holder. This function emits the FunderAbortRequested event, /// but stores no additional state. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( self.depositOwner() == msg.sender, "Only TDT holder can request funder abort" ); self.requestFunderAbort(_abortOutputScript); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key to prove fraud during funding. Note that during /// funding no signature has been requested from the signers, so /// any signature is effectively fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideFundingECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Anyone may submit a funding proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// to the signer-controlled private key corresopnding to this /// deposit. This will move the deposit into an active state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector /// (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideBTCFundingProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //---------------------------- LIQUIDATION FLOW ------------------------------// /// @notice Notify the contract that the signers are undercollateralized. /// @dev This call will revert if the signers are not in fact /// undercollateralized according to the price feed. After /// TBTCConstants.COURTESY_CALL_DURATION, courtesy call times out and /// regular abort liquidation occurs; see /// `notifyCourtesyTimedOut`. function notifyCourtesyCall() external { self.notifyCourtesyCall(); } /// @notice Notify the contract that the signers' bond value has recovered /// enough to be considered sufficiently collateralized. /// @dev This call will revert if collateral is still below the /// undercollateralized threshold according to the price feed. function exitCourtesyCall() external { self.exitCourtesyCall(); } /// @notice Notify the contract that the courtesy period has expired and the /// deposit should move into liquidation. /// @dev This call will revert if the courtesy call period has not in fact /// expired or is not in the courtesy call state. Courtesy call /// expiration is treated as an abort, and is handled by seizing signer /// bonds and putting them up for auction for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for 50% of any bond left after the /// auction is completed. function notifyCourtesyCallExpired() external { self.notifyCourtesyCallExpired(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @dev This call will revert if the signers are not in fact severely /// undercollateralized according to the price feed. Severe /// undercollateralization is treated as an abort, and is handled by /// seizing signer bonds and putting them up for auction in exchange /// for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and is /// eligible for 50% of any bond left after the auction is completed. function notifyUndercollateralizedLiquidation() external { self.notifyUndercollateralizedLiquidation(); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key that was not requested to prove fraud. A redemption /// request and a redemption fee increase are the only ways to /// request a signature from the signers. /// @dev This call will revert if the underlying keep cannot verify that /// there was fraud. Fraud is handled by seizing signer bonds and /// putting them up for auction in exchange for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for any bond left after the auction is /// completed. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Notify the contract that the signers have failed to produce a /// signature for a redemption request in the allotted time. /// @dev This is considered an abort, and is punished by seizing signer /// bonds and putting them up for auction. Emits a LiquidationStarted /// event and a Liquidated event and sends the full signer bond to the /// redeemer. Reverts if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. The caller /// is captured as the liquidation initiator, and is eligible for 50% /// of any bond left after the auction is completed. function notifyRedemptionSignatureTimedOut() external { self.notifyRedemptionSignatureTimedOut(); } /// @notice Notify the contract that the deposit has failed to receive a /// redemption proof in the allotted time. /// @dev This call will revert if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. This is /// considered an abort, and is punished by seizing signer bonds and /// putting them up for auction for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and /// is eligible for 50% of any bond left after the auction is /// completed. function notifyRedemptionProofTimedOut() external { self.notifyRedemptionProofTimedOut(); } /// @notice Closes an auction and purchases the signer bonds by transferring /// the lot size in TBTC to the redeemer, if there is one, or to the /// TDT holder if not. Any bond amount that is not currently up for /// auction is either made available for the liquidation initiator /// to withdraw (for fraud) or split 50-50 between the initiator and /// the signers (for abort or collateralization issues). /// @dev The amount of ETH given for the transferred TBTC can be read using /// the `auctionValue` function; note, however, that the function's /// value is only static during the specific block it is queried, as it /// varies by block timestamp. function purchaseSignerBondsAtAuction() external { self.purchaseSignerBondsAtAuction(); } //---------------------------- REDEMPTION FLOW -------------------------------// /// @notice Get TBTC amount required for redemption by a specified /// _redeemer. /// @dev This call will revert if redemption is not possible by _redeemer. /// @param _redeemer The deposit redeemer whose TBTC requirement is being /// requested. /// @return The amount in TBTC needed by the `_redeemer` to redeem the /// deposit. function getRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, false); return tbtcPayment; } /// @notice Get TBTC amount required for redemption assuming _redeemer /// is this deposit's owner (TDT holder). /// @param _redeemer The assumed owner of the deposit's TDT . /// @return The amount in TBTC needed to redeem the deposit. function getOwnerRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, true); return tbtcPayment; } /// @notice Requests redemption of this deposit, meaning the transmission, /// by the signers, of the deposit's UTXO to the specified Bitocin /// output script. Requires approving the deposit to spend the /// amount of TBTC needed to redeem. /// @dev The amount of TBTC needed to redeem can be looked up using the /// `getRedemptionTbtcRequirement` or `getOwnerRedemptionTbtcRequirement` /// functions. /// @param _outputValueBytes The 8-byte little-endian output size. The /// difference between this value and the lot size of the deposit /// will be paid as a fee to the Bitcoin miners when the signed /// transaction is broadcast. /// @param _redeemerOutputScript The redeemer's length-prefixed output /// script. function requestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters self.requestRedemption(_outputValueBytes, _redeemerOutputScript); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this function is not called /// correctly within `TBTCConstants.REDEMPTION_SIGNATURE_TIMEOUT` /// seconds of a redemption request or fee increase being received. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 /// curve's order. function provideRedemptionSignature( uint8 _v, bytes32 _r, bytes32 _s ) external { self.provideRedemptionSignature(_v, _r, _s); } /// @notice Anyone may request a signature for a transaction with an /// increased Bitcoin transaction fee. /// @dev This call will revert if the fee is already at its maximum, or if /// the new requested fee is not a multiple of the initial requested /// fee. Transaction fees can only be bumped by the amount of the /// initial requested fee. Calling this sends the deposit back to /// the `AWAITING_WITHDRAWAL_SIGNATURE` state and requires the signers /// to `provideRedemptionSignature` for the new output value in a /// timely fashion. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) external { self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes); } /// @notice Anyone may submit a redemption proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// from the signer-controlled private key corresponding to this /// deposit to the requested redemption output script. This will /// move the deposit into a redeemed state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. Signers can have their bonds seized if this is not /// called within `TBTCConstants.REDEMPTION_PROOF_TIMEOUT` seconds of /// a redemption signature being provided. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideRedemptionProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideRedemptionProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //--------------------------- MUTATING HELPERS -------------------------------// /// @notice This function can only be called by the deposit factory; use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev Initializes a new deposit clone with the base state for the /// deposit. /// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`. /// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`. /// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in /// `TBTCDepositToken`. /// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in /// `FeeRebateToken`. /// @param _vendingMachineAddress `VendingMachine` address. More info in /// `VendingMachine`. /// @param _lotSizeSatoshis The minimum amount of satoshi the funder is /// required to send. This is also the amount of /// TBTC the TDT holder will be eligible to mint: /// (10**7 satoshi == 0.1 BTC == 0.1 TBTC). function initializeDeposit( ITBTCSystem _tbtcSystem, TBTCToken _tbtcToken, IERC721 _tbtcDepositToken, FeeRebateToken _feeRebateToken, address _vendingMachineAddress, uint64 _lotSizeSatoshis ) public onlyFactory payable { self.tbtcSystem = _tbtcSystem; self.tbtcToken = _tbtcToken; self.tbtcDepositToken = _tbtcDepositToken; self.feeRebateToken = _feeRebateToken; self.vendingMachineAddress = _vendingMachineAddress; self.initialize(_lotSizeSatoshis); } /// @notice This function can only be called by the vending machine. /// @dev Performs the same action as requestRedemption, but transfers /// ownership of the deposit to the specified _finalRecipient. Used as /// a utility helper for the vending machine's shortcut /// TBTC->redemption path. /// @param _outputValueBytes The 8-byte little-endian output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters require( msg.sender == self.vendingMachineAddress, "Only the vending machine can call transferAndRequestRedemption" ); self.transferAndRequestRedemption( _outputValueBytes, _redeemerOutputScript, _finalRecipient ); } /// @notice Withdraw the ETH balance of the deposit allotted to the caller. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds() external { self.withdrawFunds(); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; library DepositLiquidation { using BTCUtils for bytes; using BytesLib for bytes; using SafeMath for uint256; using SafeMath for uint64; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Notifies the keep contract of fraud. Reverts if not fraud. /// @dev Calls out to the keep contract. this could get expensive if preimage /// is large. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function submitSignatureFraud( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); } /// @notice Determines the collateralization percentage of the signing group. /// @dev Compares the bond value and lot value. /// @param _d Deposit storage pointer. /// @return Collateralization percentage as uint. function collateralizationPercentage(DepositUtils.Deposit storage _d) public view returns (uint256) { // Determine value of the lot in wei uint256 _satoshiPrice = _d.fetchBitcoinPrice(); uint64 _lotSizeSatoshis = _d.lotSizeSatoshis; uint256 _lotValue = _lotSizeSatoshis.mul(_satoshiPrice); // Amount of wei the signers have uint256 _bondValue = _d.fetchBondAmount(); // This converts into a percentage return (_bondValue.mul(100).div(_lotValue)); } /// @dev Starts signer liquidation by seizing signer bonds. /// If the deposit is currently being redeemed, the redeemer /// receives the full bond value; otherwise, a falling price auction /// begins to buy 1 TBTC in exchange for a portion of the seized bonds; /// see purchaseSignerBondsAtAuction(). /// @param _wasFraud True if liquidation is being started due to fraud, false if for any other reason. /// @param _d Deposit storage pointer. function startLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) internal { _d.logStartedLiquidation(_wasFraud); uint256 seized = _d.seizeSignerBonds(); address redeemerAddress = _d.redeemerAddress; // Reclaim used state for gas savings _d.redemptionTeardown(); // If we see fraud in the redemption flow, we shouldn't go to auction. // Instead give the full signer bond directly to the redeemer. if (_d.inRedemption() && _wasFraud) { _d.setLiquidated(); _d.enableWithdrawal(redeemerAddress, seized); _d.logLiquidated(); return; } _d.liquidationInitiator = msg.sender; _d.liquidationInitiated = block.timestamp; // Store the timestamp for auction if(_wasFraud){ _d.setFraudLiquidationInProgress(); } else{ _d.setLiquidationInProgress(); } } /// @notice Anyone can provide a signature that was not requested to prove fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( !_d.inFunding(), "Use provideFundingECDSAFraudProof instead" ); require( !_d.inSignerLiquidation(), "Signer liquidation already in progress" ); require(!_d.inEndState(), "Contract has halted"); submitSignatureFraud(_d, _v, _r, _s, _signedDigest, _preimage); startLiquidation(_d, true); } /// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud. /// @dev For interface, reading auctionValue will give a past value. the current is better. /// @param _d Deposit storage pointer. function purchaseSignerBondsAtAuction(DepositUtils.Deposit storage _d) external { bool _wasFraud = _d.inFraudLiquidationInProgress(); require(_d.inSignerLiquidation(), "No active auction"); _d.setLiquidated(); _d.logLiquidated(); // Send the TBTC to the redeemer if they exist, otherwise to the TDT // holder. If the TDT holder is the Vending Machine, burn it to maintain // the peg. This is because, if there is a redeemer set here, the TDT // holder has already been made whole at redemption request time. address tbtcRecipient = _d.redeemerAddress; if (tbtcRecipient == address(0)) { tbtcRecipient = _d.depositOwner(); } uint256 lotSizeTbtc = _d.lotSizeTbtc(); require(_d.tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt"); if(tbtcRecipient == _d.vendingMachineAddress){ _d.tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size } else{ _d.tbtcToken.transferFrom(msg.sender, tbtcRecipient, lotSizeTbtc); } // Distribute funds to auction buyer uint256 valueToDistribute = _d.auctionValue(); _d.enableWithdrawal(msg.sender, valueToDistribute); // Send any TBTC left to the Fee Rebate Token holder _d.distributeFeeRebate(); // For fraud, pay remainder to the liquidation initiator. // For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1, // division will yield a 0 value which causes a revert; instead, // we simply ignore such a tiny amount and leave some wei dust in escrow uint256 contractEthBalance = address(this).balance; address payable initiator = _d.liquidationInitiator; if (initiator == address(0)){ initiator = address(0xdead); } if (contractEthBalance > valueToDistribute + 1) { uint256 remainingUnallocated = contractEthBalance.sub(valueToDistribute); if (_wasFraud) { _d.enableWithdrawal(initiator, remainingUnallocated); } else { // There will always be a liquidation initiator. uint256 split = remainingUnallocated.div(2); _d.pushFundsToKeepGroup(split); _d.enableWithdrawal(initiator, remainingUnallocated.sub(split)); } } } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inActive(), "Can only courtesy call from active state"); require(collateralizationPercentage(_d) < _d.undercollateralizedThresholdPercent, "Signers have sufficient collateral"); _d.courtesyCallInitiated = block.timestamp; _d.setCourtesyCall(); _d.logCourtesyCalled(); } /// @notice Goes from courtesy call to active. /// @dev Only callable if collateral is sufficient and the deposit is not expiring. /// @param _d Deposit storage pointer. function exitCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not currently in courtesy call"); require(collateralizationPercentage(_d) >= _d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized"); _d.setActive(); _d.logExitedCourtesyCall(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyUndercollateralizedLiquidation(DepositUtils.Deposit storage _d) external { require(_d.inRedeemableState(), "Deposit not in active or courtesy call"); require(collateralizationPercentage(_d) < _d.severelyUndercollateralizedThresholdPercent, "Deposit has sufficient collateral"); startLiquidation(_d, false); } /// @notice Notifies the contract that the courtesy period has elapsed. /// @dev This is treated as an abort, rather than fraud. /// @param _d Deposit storage pointer. function notifyCourtesyCallExpired(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not in a courtesy call period"); require(block.timestamp >= _d.courtesyCallInitiated.add(TBTCConstants.getCourtesyCallTimeout()), "Courtesy period has not elapsed"); startLiquidation(_d, false); } } pragma solidity ^0.5.10; /** @title BitcoinSPV */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; // The target at minimum Difficulty. Also the target of the genesis block uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000; uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /* ***** */ /* UTILS */ /* ***** */ /// @notice Determines the length of a VarInt in bytes /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length /// @param _flag The first byte of a VarInt /// @return The number of non-flag bytes in the VarInt function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) { if (uint8(_flag[0]) == 0xff) { return 8; // one-byte flag, 8 bytes data } if (uint8(_flag[0]) == 0xfe) { return 4; // one-byte flag, 4 bytes data } if (uint8(_flag[0]) == 0xfd) { return 2; // one-byte flag, 2 bytes data } return 0; // flag is data } /// @notice Parse a VarInt into its data length and the number it represents /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes. /// Caller SHOULD explicitly handle this case (or bubble it up) /// @param _b A byte-string starting with a VarInt /// @return number of bytes in the encoding (not counting the tag), the encoded int function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) { uint8 _dataLen = determineVarIntDataLength(_b); if (_dataLen == 0) { return (0, uint8(_b[0])); } if (_b.length < 1 + _dataLen) { return (ERR_BAD_ARG, 0); } uint256 _number = bytesToUint(reverseEndianness(_b.slice(1, _dataLen))); return (_dataLen, _number); } /// @notice Changes the endianness of a byte array /// @dev Returns a new, backwards, bytes /// @param _b The bytes to reverse /// @return The reversed bytes function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) { bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } /// @notice Changes the endianness of a uint256 /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel /// @param _b The unsigned integer to reverse /// @return 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 Converts big-endian bytes to a uint /// @dev Traverses the byte array and sums the bytes /// @param _b The big-endian bytes-encoded integer /// @return The integer representation function bytesToUint(bytes memory _b) internal pure returns (uint256) { uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } /// @notice Get the last _num bytes from a byte array /// @param _b The byte array to slice /// @param _num The number of bytes to extract from the end /// @return The last _num bytes of _b function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { uint256 _start = _b.length.sub(_num); return _b.slice(_start, _num); } /// @notice Implements bitcoin's hash160 (rmd160(sha2())) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash160(bytes memory _b) internal pure returns (bytes memory) { return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash256(bytes memory _b) internal pure returns (bytes32) { return sha256(abi.encodePacked(sha256(_b))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev sha2 is precompiled smart contract located at address(2) /// @param _b The pre-image /// @return The digest function hash256View(bytes memory _b) internal view returns (bytes32 res) { // solium-disable-next-line security/no-inline-assembly assembly { let ptr := mload(0x40) pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32)) pop(staticcall(gas, 2, ptr, 32, ptr, 32)) res := mload(ptr) } } /* ************ */ /* Legacy Input */ /* ************ */ /// @notice Extracts the nth input from the vin (0-indexed) /// @dev Iterates over the vin. If you need to extract several, write a custom function /// @param _vin The vin as a tightly-packed byte array /// @param _index The 0-indexed location of the input to extract /// @return The input as a byte array function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nIns, "Vin read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); _offset = _offset + _len; } _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _vin.slice(_offset, _len); } /// @notice Determines whether an input is legacy /// @dev False if no scriptSig, otherwise True /// @param _input The input /// @return True for legacy, False for witness function isLegacyInput(bytes memory _input) internal pure returns (bool) { return _input.keccak256Slice(36, 1) != keccak256(hex"00"); } /// @notice Determines the length of a scriptSig in an input /// @dev Will return 0 if passed a witness input. /// @param _input The LEGACY input /// @return The length of the script sig function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) { if (_input.length < 37) { return (ERR_BAD_ARG, 0); } bytes memory _afterOutpoint = _input.slice(36, _input.length - 36); uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = parseVarInt(_afterOutpoint); return (_varIntDataLen, _scriptSigLen); } /// @notice Determines the length of an input from its scriptSig /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence /// @param _input The input /// @return The length of the input in bytes function determineInputLength(bytes memory _input) internal pure returns (uint256) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The LEGACY input /// @return The sequence bytes (LE uint) function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } /// @notice Extracts the sequence from the input /// @dev Sequence is a 4-byte little-endian number /// @param _input The LEGACY input /// @return The sequence number (big-endian uint) function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLELegacy(_input); bytes memory _beSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_beSequence)); } /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx /// @dev Will return hex"00" if passed a witness input /// @param _input The LEGACY input /// @return The length-prepended scriptSig function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen); } /* ************* */ /* Witness Input */ /* ************* */ /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The WITNESS input /// @return The sequence bytes (LE uint) function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(37, 4); } /// @notice Extracts the sequence from the input in a tx /// @dev Sequence is a 4-byte little-endian number /// @param _input The WITNESS input /// @return The sequence number (big-endian uint) function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLEWitness(_input); bytes memory _inputeSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_inputeSequence)); } /// @notice Extracts the outpoint from the input in a tx /// @dev 32-byte tx id with 4-byte index /// @param _input The input /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index) function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(0, 36); } /// @notice Extracts the outpoint tx id from an input /// @dev 32-byte tx id /// @param _input The input /// @return The tx id (little-endian bytes) function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) { return _input.slice(0, 32).toBytes32(); } /// @notice Extracts the LE tx input index from the input in a tx /// @dev 4-byte tx index /// @param _input The input /// @return The tx index (little-endian bytes) function extractTxIndexLE(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(32, 4); } /* ****** */ /* Output */ /* ****** */ /// @notice Determines the length of an output /// @dev Works with any properly formatted output /// @param _output The output /// @return The length indicated by the prefix, error if invalid length function determineOutputLength(bytes memory _output) internal pure returns (uint256) { if (_output.length < 9) { return ERR_BAD_ARG; } bytes memory _afterValue = _output.slice(8, _output.length - 8); uint256 _varIntDataLen; uint256 _scriptPubkeyLength; (_varIntDataLen, _scriptPubkeyLength) = parseVarInt(_afterValue); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } // 8-byte value, 1-byte for tag itself return 8 + 1 + _varIntDataLen + _scriptPubkeyLength; } /// @notice Extracts the output at a given index in the TxOuts vector /// @dev Iterates over the vout. If you need to extract multiple, write a custom function /// @param _vout The _vout to extract from /// @param _index The 0-indexed location of the output to extract /// @return The specified output function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nOuts, "Vout read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); _offset += _len; } _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); return _vout.slice(_offset, _len); } /// @notice Extracts the value bytes from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value as LE bytes function extractValueLE(bytes memory _output) internal pure returns (bytes memory) { return _output.slice(0, 8); } /// @notice Extracts the value from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value function extractValue(bytes memory _output) internal pure returns (uint64) { bytes memory _leValue = extractValueLE(_output); bytes memory _beValue = reverseEndianness(_leValue); return uint64(bytesToUint(_beValue)); } /// @notice Extracts the data from an op return output /// @dev Returns hex"" if no data or not an op return /// @param _output The output /// @return Any data contained in the opreturn output, null if not an op return function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) { if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.slice(10, 1); return _output.slice(11, bytesToUint(_dataLen)); } /// @notice Extracts the hash from the output script /// @dev Determines type by the length prefix and validates format /// @param _output The output /// @return The hash committed to by the pk_script, or null for errors function extractHash(bytes memory _output) internal pure returns (bytes memory) { uint8 _scriptLen = uint8(_output[8]); // don't have to worry about overflow here. // if _scriptLen + 9 overflows, then output.length would have to be < 9 // for this check to pass. if it's < 9, then we errored when assigning // _scriptLen if (_scriptLen + 9 != _output.length) { return hex""; } if (uint8(_output[9]) == 0) { if (_scriptLen < 2) { return hex""; } uint256 _payloadLen = uint8(_output[10]); // Check for maliciously formatted witness outputs. // No need to worry about underflow as long b/c of the `< 2` check if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) { return hex""; } return _output.slice(11, _payloadLen); } else { bytes32 _tag = _output.keccak256Slice(8, 3); // p2pkh if (_tag == keccak256(hex"1976a9")) { // Check for maliciously formatted p2pkh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[11]) != 0x14 || _output.keccak256Slice(_output.length - 2, 2) != keccak256(hex"88ac")) { return hex""; } return _output.slice(12, 20); //p2sh } else if (_tag == keccak256(hex"17a914")) { // Check for maliciously formatted p2sh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[_output.length - 1]) != 0x87) { return hex""; } return _output.slice(11, 20); } } return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */ } /* ********** */ /* Witness TX */ /* ********** */ /// @notice Checks that the vin passed up is properly formatted /// @dev Consider a vin with a valid vout in its scriptsig /// @param _vin Raw bytes length-prefixed input vector /// @return True if it represents a validly formatted vin function validateVin(bytes memory _vin) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); // Not valid if it says there are too many or no inputs if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nIns; i++) { // If we're at the end, but still expect more if (_offset >= _vin.length) { return false; } // Grab the next input and determine its length. bytes memory _next = _vin.slice(_offset, _vin.length - _offset); uint256 _nextLen = determineInputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } // Increase the offset by that much _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vin.length; } /// @notice Checks that the vout passed up is properly formatted /// @dev Consider a vout with a valid scriptpubkey /// @param _vout Raw bytes length-prefixed output vector /// @return True if it represents a validly formatted vout function validateVout(bytes memory _vout) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); // Not valid if it says there are too many or no outputs if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nOuts; i++) { // If we're at the end, but still expect more if (_offset >= _vout.length) { return false; } // Grab the next output and determine its length. // Increase the offset by that much bytes memory _next = _vout.slice(_offset, _vout.length - _offset); uint256 _nextLen = determineOutputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vout.length; } /* ************ */ /* Block Header */ /* ************ */ /// @notice Extracts the transaction merkle root from a block header /// @dev Use verifyHash256Merkle to verify proofs with this root /// @param _header The header /// @return The merkle root (little-endian) function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(36, 32); } /// @notice Extracts the target from a block header /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _header The header /// @return The target threshold function extractTarget(bytes memory _header) internal pure returns (uint256) { bytes memory _m = _header.slice(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = bytesToUint(reverseEndianness(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } /// @notice Calculate difficulty from the difficulty 1 target and current target /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _target The current target /// @return The block difficulty (bdiff) function calculateDifficulty(uint256 _target) internal pure returns (uint256) { // Difficulty 1 calculated from 0x1d00ffff return DIFF1_TARGET.div(_target); } /// @notice Extracts the previous block's hash from a block header /// @dev Block headers do NOT include block number :( /// @param _header The header /// @return The previous block's hash (little-endian) function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(4, 32); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (little-endian bytes) function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(68, 4); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (uint) function extractTimestamp(bytes memory _header) internal pure returns (uint32) { return uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header)))); } /// @notice Extracts the expected difficulty from a block header /// @dev Does NOT verify the work /// @param _header The header /// @return The difficulty as an integer function extractDifficulty(bytes memory _header) internal pure returns (uint256) { return calculateDifficulty(extractTarget(_header)); } /// @notice Concatenates and hashes two inputs for merkle proving /// @param _a The first hash /// @param _b The second hash /// @return The double-sha256 of the concatenated hashes function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { return hash256(abi.encodePacked(_a, _b)); } /// @notice Verifies a Bitcoin-style merkle tree /// @dev Leaves are 0-indexed. /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root /// @param _index The index of the leaf /// @return true if the proof is valid, else false function verifyHash256Merkle(bytes memory _proof, uint _index) internal pure returns (bool) { // Not an even number of hashes if (_proof.length % 32 != 0) { return false; } // Special case for coinbase-only blocks if (_proof.length == 32) { return true; } // Should never occur if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32(); bytes32 _current = _proof.slice(0, 32).toBytes32(); for (uint i = 1; i < (_proof.length.div(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _hash256MerkleStep(_proof.slice(i * 32, 32), abi.encodePacked(_current)); } else { _current = _hash256MerkleStep(abi.encodePacked(_current), _proof.slice(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } /* NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72 NB: We get a full-bitlength target from this. For comparison with header-encoded targets we need to mask it with the header target e.g. (full & truncated) == truncated */ /// @notice performs the bitcoin difficulty retarget /// @dev implements the Bitcoin algorithm precisely /// @param _previousTarget the target of the previous period /// @param _firstTimestamp the timestamp of the first block in the difficulty period /// @param _secondTimestamp the timestamp of the last block in the difficulty period /// @return the new period's target threshold function retargetAlgorithm( uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp); // Normalize ratio to factor of 4 if very long or very short if (_elapsedTime < RETARGET_PERIOD.div(4)) { _elapsedTime = RETARGET_PERIOD.div(4); } if (_elapsedTime > RETARGET_PERIOD.mul(4)) { _elapsedTime = RETARGET_PERIOD.mul(4); } /* NB: high targets e.g. ffff0020 can cause overflows here so we divide it by 256**2, then multiply by 256**2 later we know the target is evenly divisible by 256**2, so this isn't an issue */ uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime); return _adjusted.div(RETARGET_PERIOD).mul(65536); } } pragma solidity ^0.5.10; /* https://github.com/GNSPS/solidity-bytes-utils/ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <https://unlicense.org> */ /** @title BytesLib **/ /** @author https://github.com/GNSPS **/ library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) { if (_length == 0) { return hex""; } uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { // Alloc bytes array with additional 32 bytes afterspace and assign it's size res := mload(0x40) mstore(0x40, add(add(res, 64), _length)) mstore(res, _length) // Compute distance between source and destination pointers let diff := sub(res, add(_bytes, _start)) for { let src := add(add(_bytes, 32), _start) let end := add(src, _length) } lt(src, end) { src := add(src, 32) } { mstore(add(src, diff), mload(src)) } } } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { uint _totalLen = _start + 20; require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint _totalLen = _start + 32; require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } function toBytes32(bytes memory _source) pure internal returns (bytes32 result) { if (_source.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) { uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { result := keccak256(add(add(_bytes, 32), _start), _length) } } } 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; } } pragma solidity 0.5.17; import {DepositUtils} from "./DepositUtils.sol"; library DepositStates { enum States { // DOES NOT EXIST YET START, // FUNDING FLOW AWAITING_SIGNER_SETUP, AWAITING_BTC_FUNDING_PROOF, // FAILED SETUP FAILED_SETUP, // ACTIVE ACTIVE, // includes courtesy call // REDEMPTION FLOW AWAITING_WITHDRAWAL_SIGNATURE, AWAITING_WITHDRAWAL_PROOF, REDEEMED, // SIGNER LIQUIDATION FLOW COURTESY_CALL, FRAUD_LIQUIDATION_IN_PROGRESS, LIQUIDATION_IN_PROGRESS, LIQUIDATED } /// @notice Check if the contract is currently in the funding flow. /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the funding flow else False. function inFunding(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_SIGNER_SETUP) || _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF) ); } /// @notice Check if the contract is currently in the signer liquidation flow. /// @dev This could be caused by fraud, or by an unfilled margin call. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the liquidaton flow else False. function inSignerLiquidation(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS) || _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS) ); } /// @notice Check if the contract is currently in the redepmtion flow. /// @dev This checks on the redemption flow, not the REDEEMED termination state. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the redemption flow else False. function inRedemption(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE) || _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF) ); } /// @notice Check if the contract has halted. /// @dev This checks on any halt state, regardless of triggering circumstances. /// @param _d Deposit storage pointer. /// @return True if contract has halted permanently. function inEndState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATED) || _d.currentState == uint8(States.REDEEMED) || _d.currentState == uint8(States.FAILED_SETUP) ); } /// @notice Check if the contract is available for a redemption request. /// @dev Redemption is available from active and courtesy call. /// @param _d Deposit storage pointer. /// @return True if available, False otherwise. function inRedeemableState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.ACTIVE) || _d.currentState == uint8(States.COURTESY_CALL) ); } /// @notice Check if the contract is currently in the start state (awaiting setup). /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the start state else False. function inStart(DepositUtils.Deposit storage _d) public view returns (bool) { return (_d.currentState == uint8(States.START)); } function inAwaitingSignerSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_SIGNER_SETUP); } function inAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF); } function inFailedSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FAILED_SETUP); } function inActive(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.ACTIVE); } function inAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function inAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF); } function inRedeemed(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.REDEEMED); } function inCourtesyCall(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.COURTESY_CALL); } function inFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function inLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS); } function inLiquidated(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATED); } function setAwaitingSignerSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_SIGNER_SETUP); } function setAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_BTC_FUNDING_PROOF); } function setFailedSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FAILED_SETUP); } function setActive(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.ACTIVE); } function setAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function setAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_PROOF); } function setRedeemed(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.REDEEMED); } function setCourtesyCall(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.COURTESY_CALL); } function setFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function setLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATION_IN_PROGRESS); } function setLiquidated(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATED); } } pragma solidity 0.5.17; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; library DepositUtils { using SafeMath for uint256; using SafeMath for uint64; using BytesLib for bytes; using BTCUtils for bytes; using BTCUtils for uint256; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositStates for DepositUtils.Deposit; struct Deposit { // SET DURING CONSTRUCTION ITBTCSystem tbtcSystem; TBTCToken tbtcToken; IERC721 tbtcDepositToken; FeeRebateToken feeRebateToken; address vendingMachineAddress; uint64 lotSizeSatoshis; uint8 currentState; uint16 signerFeeDivisor; uint16 initialCollateralizedPercent; uint16 undercollateralizedThresholdPercent; uint16 severelyUndercollateralizedThresholdPercent; uint256 keepSetupFee; // SET ON FRAUD uint256 liquidationInitiated; // Timestamp of when liquidation starts uint256 courtesyCallInitiated; // When the courtesy call is issued address payable liquidationInitiator; // written when we request a keep address keepAddress; // The address of our keep contract uint256 signingGroupRequestedAt; // timestamp of signing group request // written when we get a keep result uint256 fundingProofTimerStart; // start of the funding proof period. reused for funding fraud proof period bytes32 signingGroupPubkeyX; // The X coordinate of the signing group's pubkey bytes32 signingGroupPubkeyY; // The Y coordinate of the signing group's pubkey // INITIALLY WRITTEN BY REDEMPTION FLOW address payable redeemerAddress; // The redeemer's address, used as fallback for fraud in redemption bytes redeemerOutputScript; // The redeemer output script uint256 initialRedemptionFee; // the initial fee as requested uint256 latestRedemptionFee; // the fee currently required by a redemption transaction uint256 withdrawalRequestTime; // the most recent withdrawal request timestamp bytes32 lastRequestedDigest; // the digest most recently requested for signing // written when we get funded bytes8 utxoValueBytes; // LE uint. the size of the deposit UTXO in satoshis uint256 fundedAt; // timestamp when funding proof was received bytes utxoOutpoint; // the 36-byte outpoint of the custodied UTXO /// @dev Map of ETH balances an address can withdraw after contract reaches ends-state. mapping(address => uint256) withdrawableAmounts; /// @dev Map of timestamps representing when transaction digests were approved for signing mapping (bytes32 => uint256) approvedDigests; } /// @notice Closes keep associated with the deposit. /// @dev Should be called when the keep is no longer needed and the signing /// group can disband. function closeKeep(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.closeKeep(); } /// @notice Gets the current block difficulty. /// @dev Calls the light relay and gets the current block difficulty. /// @return The difficulty. function currentBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayCurrentDifficulty(); } /// @notice Gets the previous block difficulty. /// @dev Calls the light relay and gets the previous block difficulty. /// @return The difficulty. function previousBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayPreviousDifficulty(); } /// @notice Evaluates the header difficulties in a proof. /// @dev Uses the light oracle to source recent difficulty. /// @param _bitcoinHeaders The header chain to evaluate. /// @return True if acceptable, otherwise revert. function evaluateProofDifficulty(Deposit storage _d, bytes memory _bitcoinHeaders) public view { uint256 _reqDiff; uint256 _current = currentBlockDifficulty(_d); uint256 _previous = previousBlockDifficulty(_d); uint256 _firstHeaderDiff = _bitcoinHeaders.extractTarget().calculateDifficulty(); if (_firstHeaderDiff == _current) { _reqDiff = _current; } else if (_firstHeaderDiff == _previous) { _reqDiff = _previous; } else { revert("not at current or previous difficulty"); } uint256 _observedDiff = _bitcoinHeaders.validateHeaderChain(); require(_observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain"); require(_observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain"); require(_observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header"); require( _observedDiff >= _reqDiff.mul(TBTCConstants.getTxProofDifficultyFactor()), "Insufficient accumulated difficulty in header chain" ); } /// @notice Syntactically check an SPV proof for a bitcoin transaction with its hash (ID). /// @dev Stateless SPV Proof verification documented elsewhere (see https://github.com/summa-tx/bitcoin-spv). /// @param _d Deposit storage pointer. /// @param _txId The bitcoin txid of the tx that is purportedly included in the header chain. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function checkProofFromTxId( Deposit storage _d, bytes32 _txId, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view{ require( _txId.prove( _bitcoinHeaders.extractMerkleRootLE().toBytes32(), _merkleProof, _txIndexInBlock ), "Tx merkle proof is not valid for provided header and txId"); evaluateProofDifficulty(_d, _bitcoinHeaders); } /// @notice Find and validate funding output in transaction output vector using the index. /// @dev Gets `_fundingOutputIndex` output from the output vector and validates if it is /// a p2wpkh output with public key hash matching this deposit's public key hash. /// @param _d Deposit storage pointer. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC outputs. /// @param _fundingOutputIndex Index of funding output in _txOutputVector. /// @return Funding value. function findAndParseFundingOutput( DepositUtils.Deposit storage _d, bytes memory _txOutputVector, uint8 _fundingOutputIndex ) public view returns (bytes8) { bytes8 _valueBytes; bytes memory _output; // Find the output paying the signer PKH _output = _txOutputVector.extractOutputAtIndex(_fundingOutputIndex); require( keccak256(_output.extractHash()) == keccak256(abi.encodePacked(signerPKH(_d))), "Could not identify output funding the required public key hash" ); require( _output.length == 31 && _output.keccak256Slice(8, 23) == keccak256(abi.encodePacked(hex"160014", signerPKH(_d))), "Funding transaction output type unsupported: only p2wpkh outputs are supported" ); _valueBytes = bytes8(_output.slice(0, 8).toBytes32()); return _valueBytes; } /// @notice Validates the funding tx and parses information from it. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. /// @return The 8-byte LE UTXO size in satoshi, the 36byte outpoint. function validateAndParseFundingSPVProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view returns (bytes8 _valueBytes, bytes memory _utxoOutpoint){ // not external to allow bytes memory parameters require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes32 txID = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _valueBytes = findAndParseFundingOutput(_d, _txOutputVector, _fundingOutputIndex); require(bytes8LEToUint(_valueBytes) >= _d.lotSizeSatoshis, "Deposit too small"); checkProofFromTxId(_d, txID, _merkleProof, _txIndexInBlock, _bitcoinHeaders); // The utxoOutpoint is the LE txID plus the index of the output as a 4-byte LE int // _fundingOutputIndex is a uint8, so we know it is only 1 byte // Therefore, pad with 3 more bytes _utxoOutpoint = abi.encodePacked(txID, _fundingOutputIndex, hex"000000"); } /// @notice Retreive the remaining term of the deposit /// @dev The return value is not guaranteed since block.timestmap can be lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at term function remainingTerm(DepositUtils.Deposit storage _d) public view returns(uint256){ uint256 endOfTerm = _d.fundedAt.add(TBTCConstants.getDepositTerm()); if(block.timestamp < endOfTerm ) { return endOfTerm.sub(block.timestamp); } return 0; } /// @notice Calculates the amount of value at auction right now. /// @dev We calculate the % of the auction that has elapsed, then scale the value up. /// @param _d Deposit storage pointer. /// @return The value in wei to distribute in the auction at the current time. function auctionValue(Deposit storage _d) external view returns (uint256) { uint256 _elapsed = block.timestamp.sub(_d.liquidationInitiated); uint256 _available = address(this).balance; if (_elapsed > TBTCConstants.getAuctionDuration()) { return _available; } // This should make a smooth flow from base% to 100% uint256 _basePercentage = getAuctionBasePercentage(_d); uint256 _elapsedPercentage = uint256(100).sub(_basePercentage).mul(_elapsed).div(TBTCConstants.getAuctionDuration()); uint256 _percentage = _basePercentage.add(_elapsedPercentage); return _available.mul(_percentage).div(100); } /// @notice Gets the lot size in erc20 decimal places (max 18) /// @return uint256 lot size in 10**18 decimals. function lotSizeTbtc(Deposit storage _d) public view returns (uint256){ return _d.lotSizeSatoshis.mul(TBTCConstants.getSatoshiMultiplier()); } /// @notice Determines the fees due to the signers for work performed. /// @dev Signers are paid based on the TBTC issued. /// @return Accumulated fees in 10**18 decimals. function signerFeeTbtc(Deposit storage _d) public view returns (uint256) { return lotSizeTbtc(_d).div(_d.signerFeeDivisor); } /// @notice Determines the prefix to the compressed public key. /// @dev The prefix encodes the parity of the Y coordinate. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 1-byte prefix for the compressed key. function determineCompressionPrefix(bytes32 _pubkeyY) public pure returns (bytes memory) { if(uint256(_pubkeyY) & 1 == 1) { return hex"03"; // Odd Y } else { return hex"02"; // Even Y } } /// @notice Compresses a public key. /// @dev Converts the 64-byte key to a 33-byte key, bitcoin-style. /// @param _pubkeyX The X coordinate of the public key. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 33-byte compressed pubkey. function compressPubkey(bytes32 _pubkeyX, bytes32 _pubkeyY) public pure returns (bytes memory) { return abi.encodePacked(determineCompressionPrefix(_pubkeyY), _pubkeyX); } /// @notice Returns the packed public key (64 bytes) for the signing group. /// @dev We store it as 2 bytes32, (2 slots) then repack it on demand. /// @return 64 byte public key. function signerPubkey(Deposit storage _d) external view returns (bytes memory) { return abi.encodePacked(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Returns the Bitcoin pubkeyhash (hash160) for the signing group. /// @dev This is used in bitcoin output scripts for the signers. /// @return 20-bytes public key hash. function signerPKH(Deposit storage _d) public view returns (bytes20) { bytes memory _pubkey = compressPubkey(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); bytes memory _digest = _pubkey.hash160(); return bytes20(_digest.toAddress(0)); // dirty solidity hack } /// @notice Returns the size of the deposit UTXO in satoshi. /// @dev We store the deposit as bytes8 to make signature checking easier. /// @return UTXO value in satoshi. function utxoValue(Deposit storage _d) external view returns (uint256) { return bytes8LEToUint(_d.utxoValueBytes); } /// @notice Gets the current price of Bitcoin in Ether. /// @dev Polls the price feed via the system contract. /// @return The current price of 1 sat in wei. function fetchBitcoinPrice(Deposit storage _d) external view returns (uint256) { return _d.tbtcSystem.fetchBitcoinPrice(); } /// @notice Fetches the Keep's bond amount in wei. /// @dev Calls the keep contract to do so. /// @return The amount of bonded ETH in wei. function fetchBondAmount(Deposit storage _d) external view returns (uint256) { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); return _keep.checkBondAmount(); } /// @notice Convert a LE bytes8 to a uint256. /// @dev Do this by converting to bytes, then reversing endianness, then converting to int. /// @return The uint256 represented in LE by the bytes8. function bytes8LEToUint(bytes8 _b) public pure returns (uint256) { return abi.encodePacked(_b).reverseEndianness().bytesToUint(); } /// @notice Gets timestamp of digest approval for signing. /// @dev Identifies entry in the recorded approvals by keep ID and digest pair. /// @param _digest Digest to check approval for. /// @return Timestamp from the moment of recording the digest for signing. /// Returns 0 if the digest was not approved for signing. function wasDigestApprovedForSigning(Deposit storage _d, bytes32 _digest) external view returns (uint256) { return _d.approvedDigests[_digest]; } /// @notice Looks up the Fee Rebate Token holder. /// @return The current token holder if the Token exists. /// address(0) if the token does not exist. function feeRebateTokenHolder(Deposit storage _d) public view returns (address payable) { address tokenHolder = address(0); if(_d.feeRebateToken.exists(uint256(address(this)))){ tokenHolder = address(uint160(_d.feeRebateToken.ownerOf(uint256(address(this))))); } return address(uint160(tokenHolder)); } /// @notice Looks up the deposit beneficiary by calling the tBTC system. /// @dev We cast the address to a uint256 to match the 721 standard. /// @return The current deposit beneficiary. function depositOwner(Deposit storage _d) public view returns (address payable) { return address(uint160(_d.tbtcDepositToken.ownerOf(uint256(address(this))))); } /// @notice Deletes state after termination of redemption process. /// @dev We keep around the redeemer address so we can pay them out. function redemptionTeardown(Deposit storage _d) public { _d.redeemerOutputScript = ""; _d.initialRedemptionFee = 0; _d.withdrawalRequestTime = 0; _d.lastRequestedDigest = bytes32(0); } /// @notice Get the starting percentage of the bond at auction. /// @dev This will return the same value regardless of collateral price. /// @return The percentage of the InitialCollateralizationPercent that will result /// in a 100% bond value base auction given perfect collateralization. function getAuctionBasePercentage(Deposit storage _d) internal view returns (uint256) { return uint256(10000).div(_d.initialCollateralizedPercent); } /// @notice Seize the signer bond from the keep contract. /// @dev we check our balance before and after. /// @return The amount seized in wei. function seizeSignerBonds(Deposit storage _d) internal returns (uint256) { uint256 _preCallBalance = address(this).balance; IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.seizeSignerBonds(); uint256 _postCallBalance = address(this).balance; require(_postCallBalance > _preCallBalance, "No funds received, unexpected"); return _postCallBalance.sub(_preCallBalance); } /// @notice Adds a given amount to the withdraw allowance for the address. /// @dev Withdrawals can only happen when a contract is in an end-state. function enableWithdrawal(DepositUtils.Deposit storage _d, address _withdrawer, uint256 _amount) internal { _d.withdrawableAmounts[_withdrawer] = _d.withdrawableAmounts[_withdrawer].add(_amount); } /// @notice Withdraw caller's allowance. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds(DepositUtils.Deposit storage _d) internal { uint256 available = _d.withdrawableAmounts[msg.sender]; require(_d.inEndState(), "Contract not yet terminated"); require(available > 0, "Nothing to withdraw"); require(address(this).balance >= available, "Insufficient contract balance"); // zero-out to prevent reentrancy _d.withdrawableAmounts[msg.sender] = 0; /* solium-disable-next-line security/no-call-value */ (bool ok,) = msg.sender.call.value(available)(""); require( ok, "Failed to send withdrawable amount to sender" ); } /// @notice Get the caller's withdraw allowance. /// @return The caller's withdraw allowance in wei. function getWithdrawableAmount(DepositUtils.Deposit storage _d) internal view returns (uint256) { return _d.withdrawableAmounts[msg.sender]; } /// @notice Distributes the fee rebate to the Fee Rebate Token owner. /// @dev Whenever this is called we are shutting down. function distributeFeeRebate(Deposit storage _d) internal { address rebateTokenHolder = feeRebateTokenHolder(_d); // exit the function if there is nobody to send the rebate to if(rebateTokenHolder == address(0)){ return; } // pay out the rebate if it is available if(_d.tbtcToken.balanceOf(address(this)) >= signerFeeTbtc(_d)) { _d.tbtcToken.transfer(rebateTokenHolder, signerFeeTbtc(_d)); } } /// @notice Pushes ether held by the deposit to the signer group. /// @dev Ether is returned to signing group members bonds. /// @param _ethValue The amount of ether to send. function pushFundsToKeepGroup(Deposit storage _d, uint256 _ethValue) internal { require(address(this).balance >= _ethValue, "Not enough funds to send"); if(_ethValue > 0){ IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.returnPartialSignerBonds.value(_ethValue)(); } } /// @notice Calculate TBTC amount required for redemption by a specified /// _redeemer. If _assumeRedeemerHoldTdt is true, return the /// requirement as if the redeemer holds this deposit's TDT. /// @dev Will revert if redemption is not possible by the current owner and /// _assumeRedeemerHoldsTdt was not set. Setting /// _assumeRedeemerHoldsTdt only when appropriate is the responsibility /// of the caller; as such, this function should NEVER be publicly /// exposed. /// @param _redeemer The account that should be treated as redeeming this /// deposit for the purposes of this calculation. /// @param _assumeRedeemerHoldsTdt If true, the calculation assumes that the /// specified redeemer holds the TDT. If false, the calculation /// checks the deposit owner against the specified _redeemer. Note /// that this parameter should be false for all mutating calls to /// preserve system correctness. /// @return A tuple of the amount the redeemer owes to the deposit to /// initiate redemption, the amount that is owed to the TDT holder /// when redemption is initiated, and the amount that is owed to the /// FRT holder when redemption is initiated. function calculateRedemptionTbtcAmounts( DepositUtils.Deposit storage _d, address _redeemer, bool _assumeRedeemerHoldsTdt ) internal view returns ( uint256 owedToDeposit, uint256 owedToTdtHolder, uint256 owedToFrtHolder ) { bool redeemerHoldsTdt = _assumeRedeemerHoldsTdt || depositOwner(_d) == _redeemer; bool preTerm = remainingTerm(_d) > 0 && !_d.inCourtesyCall(); require( redeemerHoldsTdt || !preTerm, "Only TDT holder can redeem unless deposit is at-term or in COURTESY_CALL" ); bool frtExists = feeRebateTokenHolder(_d) != address(0); bool redeemerHoldsFrt = feeRebateTokenHolder(_d) == _redeemer; uint256 signerFee = signerFeeTbtc(_d); uint256 feeEscrow = calculateRedemptionFeeEscrow( signerFee, preTerm, frtExists, redeemerHoldsTdt, redeemerHoldsFrt ); // Base redemption + fee = total we need to have escrowed to start // redemption. owedToDeposit = calculateBaseRedemptionCharge( lotSizeTbtc(_d), redeemerHoldsTdt ).add(feeEscrow); // Adjust the amount owed to the deposit based on any balance the // deposit already has. uint256 balance = _d.tbtcToken.balanceOf(address(this)); if (owedToDeposit > balance) { owedToDeposit = owedToDeposit.sub(balance); } else { owedToDeposit = 0; } // Pre-term, the FRT rebate is payed out, but if the redeemer holds the // FRT, the amount has already been subtracted from what is owed to the // deposit at this point (by calculateRedemptionFeeEscrow). This allows // the redeemer to simply *not pay* the fee rebate, rather than having // them pay it only to have it immediately returned. if (preTerm && frtExists && !redeemerHoldsFrt) { owedToFrtHolder = signerFee; } // The TDT holder gets any leftover balance. owedToTdtHolder = balance.add(owedToDeposit).sub(signerFee).sub(owedToFrtHolder); return (owedToDeposit, owedToTdtHolder, owedToFrtHolder); } /// @notice Get the base TBTC amount needed to redeem. /// @param _lotSize The lot size to use for the base redemption charge. /// @param _redeemerHoldsTdt True if the redeemer is the TDT holder. /// @return The amount in TBTC. function calculateBaseRedemptionCharge( uint256 _lotSize, bool _redeemerHoldsTdt ) internal pure returns (uint256){ if (_redeemerHoldsTdt) { return 0; } return _lotSize; } /// @notice Get fees owed for redemption /// @param signerFee The value of the signer fee for fee calculations. /// @param _preTerm True if the Deposit is at-term or in courtesy_call. /// @param _frtExists True if the FRT exists. /// @param _redeemerHoldsTdt True if the the redeemer holds the TDT. /// @param _redeemerHoldsFrt True if the redeemer holds the FRT. /// @return The fees owed in TBTC. function calculateRedemptionFeeEscrow( uint256 signerFee, bool _preTerm, bool _frtExists, bool _redeemerHoldsTdt, bool _redeemerHoldsFrt ) internal pure returns (uint256) { // Escrow the fee rebate so the FRT holder can be repaids, unless the // redeemer holds the FRT, in which case we simply don't require the // rebate from them. bool escrowRequiresFeeRebate = _preTerm && _frtExists && ! _redeemerHoldsFrt; bool escrowRequiresFee = _preTerm || // If the FRT exists at term/courtesy call, the fee is // "required", but should already be escrowed before redemption. _frtExists || // The TDT holder always owes fees if there is no FRT. _redeemerHoldsTdt; uint256 feeEscrow = 0; if (escrowRequiresFee) { feeEscrow += signerFee; } if (escrowRequiresFeeRebate) { feeEscrow += signerFee; } return feeEscrow; } } pragma solidity 0.5.17; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; library DepositFunding { using SafeMath for uint256; using SafeMath for uint64; using BTCUtils for bytes; using BytesLib for bytes; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Deletes state after funding. /// @dev This is called when we go to ACTIVE or setup fails without fraud. function fundingTeardown(DepositUtils.Deposit storage _d) internal { _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; } /// @notice Deletes state after the funding ECDSA fraud process. /// @dev This is only called as we transition to setup failed. function fundingFraudTeardown(DepositUtils.Deposit storage _d) internal { _d.keepAddress = address(0); _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; _d.signingGroupPubkeyX = bytes32(0); _d.signingGroupPubkeyY = bytes32(0); } /// @notice Internally called function to set up a newly created Deposit /// instance. This should not be called by developers, use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev If called directly, the transaction will revert since the call will /// be executed on an already set-up instance. /// @param _d Deposit storage pointer. /// @param _lotSizeSatoshis Lot size in satoshis. function initialize( DepositUtils.Deposit storage _d, uint64 _lotSizeSatoshis ) public { require(_d.tbtcSystem.getAllowNewDeposits(), "New deposits aren't allowed."); require(_d.inStart(), "Deposit setup already requested"); _d.lotSizeSatoshis = _lotSizeSatoshis; _d.keepSetupFee = _d.tbtcSystem.getNewDepositFeeEstimate(); // Note: this is a library, and library functions cannot be marked as // payable. Thus, we disable Solium's check that msg.value can only be // used in a payable function---this restriction actually applies to the // caller of this `initialize` function, Deposit.initializeDeposit. /* solium-disable-next-line value-in-payable */ _d.keepAddress = _d.tbtcSystem.requestNewKeep.value(msg.value)( _lotSizeSatoshis, TBTCConstants.getDepositTerm() ); require(_d.fetchBondAmount() >= _d.keepSetupFee, "Insufficient signer bonds to cover setup fee"); _d.signerFeeDivisor = _d.tbtcSystem.getSignerFeeDivisor(); _d.undercollateralizedThresholdPercent = _d.tbtcSystem.getUndercollateralizedThresholdPercent(); _d.severelyUndercollateralizedThresholdPercent = _d.tbtcSystem.getSeverelyUndercollateralizedThresholdPercent(); _d.initialCollateralizedPercent = _d.tbtcSystem.getInitialCollateralizedPercent(); _d.signingGroupRequestedAt = block.timestamp; _d.setAwaitingSignerSetup(); _d.logCreated(_d.keepAddress); } /// @notice Anyone may notify the contract that signing group setup has timed out. /// @param _d Deposit storage pointer. function notifySignerSetupFailed(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingSignerSetup(), "Not awaiting setup"); require( block.timestamp > _d.signingGroupRequestedAt.add(TBTCConstants.getSigningGroupFormationTimeout()), "Signing group formation timeout not yet elapsed" ); // refund the deposit owner the cost to create a new Deposit at the time the Deposit was opened. uint256 _seized = _d.seizeSignerBonds(); if(_seized >= _d.keepSetupFee){ /* solium-disable-next-line security/no-send */ _d.enableWithdrawal(_d.depositOwner(), _d.keepSetupFee); _d.pushFundsToKeepGroup(_seized.sub(_d.keepSetupFee)); } _d.setFailedSetup(); _d.logSetupFailed(); fundingTeardown(_d); } /// @notice we poll the Keep contract to retrieve our pubkey. /// @dev We store the pubkey as 2 bytestrings, X and Y. /// @param _d Deposit storage pointer. /// @return True if successful, otherwise revert. function retrieveSignerPubkey(DepositUtils.Deposit storage _d) public { require(_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup"); bytes memory _publicKey = IBondedECDSAKeep(_d.keepAddress).getPublicKey(); require(_publicKey.length == 64, "public key not set or not 64-bytes long"); _d.signingGroupPubkeyX = _publicKey.slice(0, 32).toBytes32(); _d.signingGroupPubkeyY = _publicKey.slice(32, 32).toBytes32(); require(_d.signingGroupPubkeyY != bytes32(0) && _d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey"); _d.fundingProofTimerStart = block.timestamp; _d.setAwaitingBTCFundingProof(); _d.logRegisteredPubkey( _d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Anyone may notify the contract that the funder has failed to /// prove that they have sent BTC in time. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Reverts if the funding timeout /// has not yet elapsed, or if the deposit is not currently awaiting /// funding proof. /// @param _d Deposit storage pointer. function notifyFundingTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingBTCFundingProof(), "Funding timeout has not started"); require( block.timestamp > _d.fundingProofTimerStart.add(TBTCConstants.getFundingTimeout()), "Funding timeout has not elapsed." ); _d.setFailedSetup(); _d.logSetupFailed(); _d.closeKeep(); fundingTeardown(_d); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests return of a sent UTXO to `_abortOutputScript`. This can /// be used for example when a UTXO is sent that is the wrong size /// for the lot. Must be called after setup fails for any reason, /// and imposes no requirement or incentive on the signing group to /// return the UTXO. /// @dev This is a self-admitted funder fault, and should only be callable /// by the TDT holder. /// @param _d Deposit storage pointer. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters require( _d.inFailedSetup(), "The deposit has not failed funding" ); _d.logFunderRequestedAbort(_abortOutputScript); } /// @notice Anyone can provide a signature that was not requested to prove fraud during funding. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. /// @return True if successful, otherwise revert. function provideFundingECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( _d.inAwaitingBTCFundingProof(), "Signer fraud during funding flow only available while awaiting funding" ); _d.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); _d.logFraudDuringSetup(); // Allow deposit owner to withdraw seized bonds after contract termination. uint256 _seized = _d.seizeSignerBonds(); _d.enableWithdrawal(_d.depositOwner(), _seized); fundingFraudTeardown(_d); _d.setFailedSetup(); _d.logSetupFailed(); } /// @notice Anyone may notify the deposit of a funding proof to activate the deposit. /// This is the happy-path of the funding flow. It means that we have succeeded. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. function provideBTCFundingProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters require(_d.inAwaitingBTCFundingProof(), "Not awaiting funding"); bytes8 _valueBytes; bytes memory _utxoOutpoint; (_valueBytes, _utxoOutpoint) = _d.validateAndParseFundingSPVProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); // Write down the UTXO info and set to active. Congratulations :) _d.utxoValueBytes = _valueBytes; _d.utxoOutpoint = _utxoOutpoint; _d.fundedAt = block.timestamp; bytes32 _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); fundingTeardown(_d); _d.setActive(); _d.logFunded(_txid); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {CheckBitcoinSigs} from "@summa-tx/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; library DepositRedemption { using SafeMath for uint256; using CheckBitcoinSigs for bytes; using BytesLib for bytes; using BTCUtils for bytes; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Pushes signer fee to the Keep group by transferring it to the Keep address. /// @dev Approves the keep contract, then expects it to call transferFrom. function distributeSignerFee(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _d.tbtcToken.approve(_d.keepAddress, _d.signerFeeTbtc()); _keep.distributeERC20Reward(address(_d.tbtcToken), _d.signerFeeTbtc()); } /// @notice Approves digest for signing by a keep. /// @dev Calls given keep to sign the digest. Records a current timestamp /// for given digest. /// @param _digest Digest to approve. function approveDigest(DepositUtils.Deposit storage _d, bytes32 _digest) internal { IBondedECDSAKeep(_d.keepAddress).sign(_digest); _d.approvedDigests[_digest] = block.timestamp; } /// @notice Handles TBTC requirements for redemption. /// @dev Burns or transfers depending on term and supply-peg impact. /// Once these transfers complete, the deposit balance should be /// sufficient to pay out signer fees once the redemption transaction /// is proven on the Bitcoin side. function performRedemptionTbtcTransfers(DepositUtils.Deposit storage _d) internal { address tdtHolder = _d.depositOwner(); address frtHolder = _d.feeRebateTokenHolder(); address vendingMachineAddress = _d.vendingMachineAddress; ( uint256 tbtcOwedToDeposit, uint256 tbtcOwedToTdtHolder, uint256 tbtcOwedToFrtHolder ) = _d.calculateRedemptionTbtcAmounts(_d.redeemerAddress, false); if(tbtcOwedToDeposit > 0){ _d.tbtcToken.transferFrom(msg.sender, address(this), tbtcOwedToDeposit); } if(tbtcOwedToTdtHolder > 0){ if(tdtHolder == vendingMachineAddress){ _d.tbtcToken.burn(tbtcOwedToTdtHolder); } else { _d.tbtcToken.transfer(tdtHolder, tbtcOwedToTdtHolder); } } if(tbtcOwedToFrtHolder > 0){ _d.tbtcToken.transfer(frtHolder, tbtcOwedToFrtHolder); } } function _requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _redeemer ) internal { require(_d.inRedeemableState(), "Redemption only available from Active or Courtesy state"); bytes memory _output = abi.encodePacked(_outputValueBytes, _redeemerOutputScript); require(_output.extractHash().length > 0, "Output script must be a standard type"); // set redeemerAddress early to enable direct access by other functions _d.redeemerAddress = _redeemer; performRedemptionTbtcTransfers(_d); // Convert the 8-byte LE ints to uint256 uint256 _outputValue = abi.encodePacked(_outputValueBytes).reverseEndianness().bytesToUint(); uint256 _requestedFee = _d.utxoValue().sub(_outputValue); require(_requestedFee >= TBTCConstants.getMinimumRedemptionFee(), "Fee is too low"); require( _requestedFee < _d.utxoValue() / 2, "Initial fee cannot exceed half of the deposit's value" ); // Calculate the sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _outputValueBytes, _redeemerOutputScript); // write all request details _d.redeemerOutputScript = _redeemerOutputScript; _d.initialRedemptionFee = _requestedFee; _d.latestRedemptionFee = _requestedFee; _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( _redeemer, _sighash, _d.utxoValue(), _redeemerOutputScript, _requestedFee, _d.utxoOutpoint); } /// @notice Anyone can request redemption as long as they can. /// approve the TDT transfer to the final recipient. /// @dev The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption /// on behalf of _finalRecipient. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters _d.tbtcDepositToken.transferFrom(msg.sender, _finalRecipient, uint256(address(this))); _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, _finalRecipient); } /// @notice Only TDT holder can request redemption, /// unless Deposit is expired or in COURTESY_CALL. /// @dev The redeemer specifies details about the Bitcoin redemption transaction. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, msg.sender); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this (or provideRedemptionProof) is not called. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 curve's order. function provideRedemptionSignature( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s ) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); // If we're outside of the signature window, we COULD punish signers here // Instead, we consider this a no-harm-no-foul situation. // The signers have not stolen funds. Most likely they've just inconvenienced someone // Validate `s` value for a malleability concern described in EIP-2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order are considered valid. require( uint256(_s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Malleable signature - s should be in the low half of secp256k1 curve's order" ); // The signature must be valid on the pubkey require( _d.signerPubkey().checkSig( _d.lastRequestedDigest, _v, _r, _s ), "Invalid signature" ); // A signature has been provided, now we wait for fee bump or redemption _d.setAwaitingWithdrawalProof(); _d.logGotRedemptionSignature( _d.lastRequestedDigest, _r, _s); } /// @notice Anyone may notify the contract that a fee bump is needed. /// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE. /// @param _d Deposit storage pointer. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public { require(_d.inAwaitingWithdrawalProof(), "Fee increase only available after signature provided"); require(block.timestamp >= _d.withdrawalRequestTime.add(TBTCConstants.getIncreaseFeeTimer()), "Fee increase not yet permitted"); uint256 _newOutputValue = checkRelationshipToPrevious(_d, _previousOutputValueBytes, _newOutputValueBytes); // If the fee bump shrinks the UTXO value below the minimum allowed // value, clamp it to that minimum. Further fee bumps will be disallowed // by checkRelationshipToPrevious. if (_newOutputValue < TBTCConstants.getMinimumUtxoValue()) { _newOutputValue = TBTCConstants.getMinimumUtxoValue(); } _d.latestRedemptionFee = _d.utxoValue().sub(_newOutputValue); // Calculate the next sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _newOutputValueBytes, _d.redeemerOutputScript); // Ratchet the signature and redemption proof timeouts _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); // Go back to waiting for a signature _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( msg.sender, _sighash, _d.utxoValue(), _d.redeemerOutputScript, _d.latestRedemptionFee, _d.utxoOutpoint); } function checkRelationshipToPrevious( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public view returns (uint256 _newOutputValue){ // Check that we're incrementing the fee by exactly the redeemer's initial fee uint256 _previousOutputValue = DepositUtils.bytes8LEToUint(_previousOutputValueBytes); _newOutputValue = DepositUtils.bytes8LEToUint(_newOutputValueBytes); require(_previousOutputValue.sub(_newOutputValue) == _d.initialRedemptionFee, "Not an allowed fee step"); // Calculate the previous one so we can check that it really is the previous one bytes32 _previousSighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _previousOutputValueBytes, _d.redeemerOutputScript); require( _d.wasDigestApprovedForSigning(_previousSighash) == _d.withdrawalRequestTime, "Provided previous value does not yield previous sighash" ); } /// @notice Anyone may provide a withdrawal proof to prove redemption. /// @dev The signers will be penalized if this is not called. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function provideRedemptionProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters bytes32 _txid; uint256 _fundingOutputValue; require(_d.inRedemption(), "Redemption proof only allowed from redemption flow"); _fundingOutputValue = redemptionTransactionChecks(_d, _txInputVector, _txOutputVector); _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _d.checkProofFromTxId(_txid, _merkleProof, _txIndexInBlock, _bitcoinHeaders); require((_d.utxoValue().sub(_fundingOutputValue)) <= _d.latestRedemptionFee, "Incorrect fee amount"); // Transfer TBTC to signers and close the keep. distributeSignerFee(_d); _d.closeKeep(); _d.distributeFeeRebate(); // We're done yey! _d.setRedeemed(); _d.redemptionTeardown(); _d.logRedeemed(_txid); } /// @notice Check the redemption transaction input and output vector to ensure the transaction spends /// the correct UTXO and sends value to the appropriate public key hash. /// @dev We only look at the first input and first output. Revert if we find the wrong UTXO or value recipient. /// It's safe to look at only the first input/output as anything that breaks this can be considered fraud /// and can be caught by ECDSAFraudProof. /// @param _d Deposit storage pointer. /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @return The value sent to the redeemer's public key hash. function redemptionTransactionChecks( DepositUtils.Deposit storage _d, bytes memory _txInputVector, bytes memory _txOutputVector ) public view returns (uint256) { require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes memory _input = _txInputVector.slice(1, _txInputVector.length-1); require( keccak256(_input.extractOutpoint()) == keccak256(_d.utxoOutpoint), "Tx spends the wrong UTXO" ); bytes memory _output = _txOutputVector.slice(1, _txOutputVector.length-1); bytes memory _expectedOutputScript = _d.redeemerOutputScript; require(_output.length - 8 >= _d.redeemerOutputScript.length, "Output script is too short to extract the expected script"); require( keccak256(_output.slice(8, _expectedOutputScript.length)) == keccak256(_expectedOutputScript), "Tx sends value to wrong output script" ); return (uint256(_output.extractValue())); } /// @notice Anyone may notify the contract that the signers have failed to produce a signature. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionSignatureTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getSignatureTimeout()), "Signature timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } /// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionProofTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalProof(), "Not currently awaiting a redemption proof"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getRedemptionProofTimeout()), "Proof timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } } pragma solidity 0.5.17; library TBTCConstants { // This is intended to make it easy to update system params // During testing swap this out with another constats contract // System Parameters uint256 public constant BENEFICIARY_FEE_DIVISOR = 1000; // 1/1000 = 10 bps = 0.1% = 0.001 uint256 public constant SATOSHI_MULTIPLIER = 10 ** 10; // multiplier to convert satoshi to TBTC token units uint256 public constant DEPOSIT_TERM_LENGTH = 180 * 24 * 60 * 60; // 180 days in seconds uint256 public constant TX_PROOF_DIFFICULTY_FACTOR = 6; // confirmations on the Bitcoin chain // Redemption Flow uint256 public constant REDEMPTION_SIGNATURE_TIMEOUT = 2 * 60 * 60; // seconds uint256 public constant INCREASE_FEE_TIMER = 4 * 60 * 60; // seconds uint256 public constant REDEMPTION_PROOF_TIMEOUT = 6 * 60 * 60; // seconds uint256 public constant MINIMUM_REDEMPTION_FEE = 2000; // satoshi uint256 public constant MINIMUM_UTXO_VALUE = 2000; // satoshi // Funding Flow uint256 public constant FUNDING_PROOF_TIMEOUT = 3 * 60 * 60; // seconds uint256 public constant FORMATION_TIMEOUT = 3 * 60 * 60; // seconds // Liquidation Flow uint256 public constant COURTESY_CALL_DURATION = 6 * 60 * 60; // seconds uint256 public constant AUCTION_DURATION = 24 * 60 * 60; // seconds // Getters for easy access function getBeneficiaryRewardDivisor() external pure returns (uint256) { return BENEFICIARY_FEE_DIVISOR; } function getSatoshiMultiplier() external pure returns (uint256) { return SATOSHI_MULTIPLIER; } function getDepositTerm() external pure returns (uint256) { return DEPOSIT_TERM_LENGTH; } function getTxProofDifficultyFactor() external pure returns (uint256) { return TX_PROOF_DIFFICULTY_FACTOR; } function getSignatureTimeout() external pure returns (uint256) { return REDEMPTION_SIGNATURE_TIMEOUT; } function getIncreaseFeeTimer() external pure returns (uint256) { return INCREASE_FEE_TIMER; } function getRedemptionProofTimeout() external pure returns (uint256) { return REDEMPTION_PROOF_TIMEOUT; } function getMinimumRedemptionFee() external pure returns (uint256) { return MINIMUM_REDEMPTION_FEE; } function getMinimumUtxoValue() external pure returns (uint256) { return MINIMUM_UTXO_VALUE; } function getFundingTimeout() external pure returns (uint256) { return FUNDING_PROOF_TIMEOUT; } function getSigningGroupFormationTimeout() external pure returns (uint256) { return FORMATION_TIMEOUT; } function getCourtesyCallTimeout() external pure returns (uint256) { return COURTESY_CALL_DURATION; } function getAuctionDuration() external pure returns (uint256) { return AUCTION_DURATION; } } pragma solidity 0.5.17; import {DepositLog} from "../DepositLog.sol"; import {DepositUtils} from "./DepositUtils.sol"; library OutsourceDepositLogging { /// @notice Fires a Created event. /// @dev `DepositLog.logCreated` fires a Created event with /// _keepAddress, msg.sender and block.timestamp. /// msg.sender will be the calling Deposit's address. /// @param _keepAddress The address of the associated keep. function logCreated(DepositUtils.Deposit storage _d, address _keepAddress) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCreated(_keepAddress); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _redeemer The ethereum address of the redeemer. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The redeemer or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( DepositUtils.Deposit storage _d, address _redeemer, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedemptionRequested( _redeemer, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest Signed digest. /// @param _r Signature r value. /// @param _s Signature s value. /// @return True if successful, else revert. function logGotRedemptionSignature( DepositUtils.Deposit storage _d, bytes32 _digest, bytes32 _r, bytes32 _s ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logGotRedemptionSignature( _digest, _r, _s ); } /// @notice Fires a RegisteredPubkey event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRegisteredPubkey( DepositUtils.Deposit storage _d, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRegisteredPubkey( _signingGroupPubkeyX, _signingGroupPubkeyY); } /// @notice Fires a SetupFailed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logSetupFailed(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logSetupFailed(); } /// @notice Fires a FunderAbortRequested event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunderRequestedAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunderRequestedAbort(_abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFraudDuringSetup(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFraudDuringSetup(); } /// @notice Fires a Funded event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunded(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunded(_txid); } /// @notice Fires a CourtesyCalled event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logCourtesyCalled(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCourtesyCalled(); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logStartedLiquidation(_wasFraud); } /// @notice Fires a Redeemed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRedeemed(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedeemed(_txid); } /// @notice Fires a Liquidated event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logLiquidated(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logLiquidated(); } /// @notice Fires a ExitedCourtesyCall event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logExitedCourtesyCall(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logExitedCourtesyCall(); } } pragma solidity 0.5.17; import {TBTCDepositToken} from "./system/TBTCDepositToken.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. contract DepositLog { /* Logging philosophy: Every state transition should fire a log That log should have ALL necessary info for off-chain actors Everyone should be able to ENTIRELY rely on log messages */ // `TBTCDepositToken` mints a token for every new Deposit. // If a token exists for a given ID, we know it is a valid Deposit address. TBTCDepositToken tbtcDepositToken; // This event is fired when we init the deposit event Created( address indexed _depositContractAddress, address indexed _keepAddress, uint256 _timestamp ); // This log event contains all info needed to rebuild the redemption tx // We index on request and signers and digest event RedemptionRequested( address indexed _depositContractAddress, address indexed _requester, bytes32 indexed _digest, uint256 _utxoValue, bytes _redeemerOutputScript, uint256 _requestedFee, bytes _outpoint ); // This log event contains all info needed to build a witnes // We index the digest so that we can search events for the other log event GotRedemptionSignature( address indexed _depositContractAddress, bytes32 indexed _digest, bytes32 _r, bytes32 _s, uint256 _timestamp ); // This log is fired when the signing group returns a public key event RegisteredPubkey( address indexed _depositContractAddress, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY, uint256 _timestamp ); // This event is fired when we enter the FAILED_SETUP state for any reason event SetupFailed( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when a funder requests funder abort after // FAILED_SETUP has been reached. Funder abort is a voluntary signer action // to return UTXO(s) that were sent to a signer-controlled wallet despite // the funding proofs having failed. event FunderAbortRequested( address indexed _depositContractAddress, bytes _abortOutputScript ); // This event is fired when we detect an ECDSA fraud before seeing a funding proof event FraudDuringSetup( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we enter the ACTIVE state event Funded( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is called when we enter the COURTESY_CALL state event CourtesyCalled( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we go from COURTESY_CALL to ACTIVE event ExitedCourtesyCall( address indexed _depositContractAddress, uint256 _timestamp ); // This log event is fired when liquidation event StartedLiquidation( address indexed _depositContractAddress, bool _wasFraud, uint256 _timestamp ); // This event is fired when the Redemption SPV proof is validated event Redeemed( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is fired when Liquidation is completed event Liquidated( address indexed _depositContractAddress, uint256 _timestamp ); // // Logging // /// @notice Fires a Created event. /// @dev We append the sender, which is the deposit contract that called. /// @param _keepAddress The address of the associated keep. /// @return True if successful, else revert. function logCreated(address _keepAddress) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Created(msg.sender, _keepAddress, block.timestamp); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _requester The ethereum address of the requester. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The requester or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( address _requester, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RedemptionRequested( msg.sender, _requester, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest signed digest. /// @param _r signature r value. /// @param _s signature s value. function logGotRedemptionSignature(bytes32 _digest, bytes32 _r, bytes32 _s) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit GotRedemptionSignature( msg.sender, _digest, _r, _s, block.timestamp ); } /// @notice Fires a RegisteredPubkey event. /// @dev We append the sender, which is the deposit contract that called. function logRegisteredPubkey( bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RegisteredPubkey( msg.sender, _signingGroupPubkeyX, _signingGroupPubkeyY, block.timestamp ); } /// @notice Fires a SetupFailed event. /// @dev We append the sender, which is the deposit contract that called. function logSetupFailed() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit SetupFailed(msg.sender, block.timestamp); } /// @notice Fires a FunderAbortRequested event. /// @dev We append the sender, which is the deposit contract that called. function logFunderRequestedAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FunderAbortRequested(msg.sender, _abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev We append the sender, which is the deposit contract that called. function logFraudDuringSetup() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FraudDuringSetup(msg.sender, block.timestamp); } /// @notice Fires a Funded event. /// @dev We append the sender, which is the deposit contract that called. function logFunded(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Funded(msg.sender, _txid, block.timestamp); } /// @notice Fires a CourtesyCalled event. /// @dev We append the sender, which is the deposit contract that called. function logCourtesyCalled() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit CourtesyCalled(msg.sender, block.timestamp); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(bool _wasFraud) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit StartedLiquidation(msg.sender, _wasFraud, block.timestamp); } /// @notice Fires a Redeemed event /// @dev We append the sender, which is the deposit contract that called. function logRedeemed(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Redeemed(msg.sender, _txid, block.timestamp); } /// @notice Fires a Liquidated event /// @dev We append the sender, which is the deposit contract that called. function logLiquidated() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Liquidated(msg.sender, block.timestamp); } /// @notice Fires a ExitedCourtesyCall event /// @dev We append the sender, which is the deposit contract that called. function logExitedCourtesyCall() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit ExitedCourtesyCall(msg.sender, block.timestamp); } /// @notice Sets the tbtcDepositToken contract. /// @dev The contract is used by `approvedToLog` to check if the /// caller is a Deposit contract. This should only be called once. /// @param _tbtcDepositTokenAddress The address of the tbtcDepositToken. function setTbtcDepositToken(TBTCDepositToken _tbtcDepositTokenAddress) internal { require( address(tbtcDepositToken) == address(0), "tbtcDepositToken is already set" ); tbtcDepositToken = _tbtcDepositTokenAddress; } // // AUTH // /// @notice Checks if an address is an allowed logger. /// @dev checks tbtcDepositToken to see if the caller represents /// an existing deposit. /// We don't require this, so deposits are not bricked if the system borks. /// @param _caller The address of the calling contract. /// @return True if approved, otherwise false. function approvedToLog(address _caller) public view returns (bool) { return tbtcDepositToken.exists(uint256(_caller)); } } pragma solidity 0.5.17; import {ERC721Metadata} from "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import {DepositFactoryAuthority} from "./DepositFactoryAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title tBTC Deposit Token for tracking deposit ownership /// @notice The tBTC Deposit Token, commonly referenced as the TDT, is an /// ERC721 non-fungible token whose ownership reflects the ownership /// of its corresponding deposit. Each deposit has one TDT, and vice /// versa. Owning a TDT is equivalent to owning its corresponding /// deposit. TDTs can be transferred freely. tBTC's VendingMachine /// contract takes ownership of TDTs and in exchange returns fungible /// TBTC tokens whose value is backed 1-to-1 by the corresponding /// deposit's BTC. /// @dev Currently, TDTs are minted using the uint256 casting of the /// corresponding deposit contract's address. That is, the TDT's id is /// convertible to the deposit's address and vice versa. TDTs are minted /// automatically by the factory during each deposit's initialization. See /// DepositFactory.createNewDeposit() for more info on how the TDT is minted. contract TBTCDepositToken is ERC721Metadata, DepositFactoryAuthority { constructor(address _depositFactoryAddress) ERC721Metadata("tBTC Deposit Token", "TDT") public { initialize(_depositFactoryAddress); } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token /// @param _tokenId uint256 ID of the token to be minted function mint(address _to, uint256 _tokenId) external onlyFactory { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /// @notice Allow another address to spend on the caller's behalf. /// Set allowance for other address and notify. /// Allows `_spender` to transfer the specified TDT /// on your behalf and then ping the contract about it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface below to receive approval notifications. /// @param _spender `ITokenRecipient`-conforming contract authorized to /// operate on the approved token. /// @param _tdtId The TDT they can spend. /// @param _extraData Extra information to send to the approved contract. function approveAndCall( ITokenRecipient _spender, uint256 _tdtId, bytes memory _extraData ) public returns (bool) { // not external to allow bytes memory parameters approve(address(_spender), _tdtId); _spender.receiveApproval(msg.sender, _tdtId, address(this), _extraData); return true; } } /* Authored by Satoshi Nakamoto 🤪 */ pragma solidity 0.5.17; import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import {ERC20Detailed} from "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import {VendingMachineAuthority} from "./VendingMachineAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title TBTC Token. /// @notice This is the TBTC ERC20 contract. /// @dev Tokens can only be minted by the `VendingMachine` contract. contract TBTCToken is ERC20Detailed, ERC20, VendingMachineAuthority { /// @dev Constructor, calls ERC20Detailed constructor to set Token info /// ERC20Detailed(TokenName, TokenSymbol, NumberOfDecimals) constructor(address _VendingMachine) ERC20Detailed("tBTC", "TBTC", 18) VendingMachineAuthority(_VendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints an amount of the token and assigns it to an account. /// Uses the internal _mint function. /// @param _account The account that will receive the created tokens. /// @param _amount The amount of tokens that will be created. function mint(address _account, uint256 _amount) public onlyVendingMachine returns (bool) { // NOTE: this is a public function with unchecked minting. _mint(_account, _amount); return true; } /// @dev Burns an amount of the token from the given account's balance. /// deducting from the sender's allowance for said account. /// Uses the internal _burn function. /// @param _account The account whose tokens will be burnt. /// @param _amount The amount of tokens that will be burnt. function burnFrom(address _account, uint256 _amount) public { _burnFrom(_account, _amount); } /// @dev Destroys `amount` tokens from `msg.sender`, reducing the /// total supply. /// @param _amount The amount of tokens that will be burnt. function burn(uint256 _amount) public { _burn(msg.sender, _amount); } /// @notice Set allowance for other address and notify. /// Allows `_spender` to spend no more than `_value` /// tokens on your behalf and then ping the contract about /// it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface to receive approval notifications. /// @param _spender Address of contract authorized to spend. /// @param _value The max amount they can spend. /// @param _extraData Extra information to send to the approved contract. /// @return true if the `_spender` was successfully approved and acted on /// the approval, false (or revert) otherwise. function approveAndCall(ITokenRecipient _spender, uint256 _value, bytes memory _extraData) public returns (bool) { if (approve(address(_spender), _value)) { _spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } return false; } } pragma solidity 0.5.17; /// @title Deposit Factory Authority /// @notice Contract to secure function calls to the Deposit Factory. /// @dev Secured by setting the depositFactory address and using the onlyFactory /// modifier on functions requiring restriction. contract DepositFactoryAuthority { bool internal _initialized = false; address internal _depositFactory; /// @notice Set the address of the System contract on contract /// initialization. /// @dev Since this function is not access-controlled, it should be called /// transactionally with contract instantiation. In cases where a /// regular contract directly inherits from DepositFactoryAuthority, /// that should happen in the constructor. In cases where the inheritor /// is binstead used via a clone factory, the same function that /// creates a new clone should also trigger initialization. function initialize(address _factory) public { require(_factory != address(0), "Factory cannot be the zero address."); require(! _initialized, "Factory can only be initialized once."); _depositFactory = _factory; _initialized = true; } /// @notice Function modifier ensures modified function is only called by set deposit factory. modifier onlyFactory(){ require(_initialized, "Factory initialization must have been called."); require(msg.sender == _depositFactory, "Caller must be depositFactory contract"); _; } } pragma solidity 0.5.17; /// @title TBTC System Authority. /// @notice Contract to secure function calls to the TBTC System contract. /// @dev The `TBTCSystem` contract address is passed as a constructor parameter. contract TBTCSystemAuthority { address internal tbtcSystemAddress; /// @notice Set the address of the System contract on contract initialization. constructor(address _tbtcSystemAddress) public { tbtcSystemAddress = _tbtcSystemAddress; } /// @notice Function modifier ensures modified function is only called by TBTCSystem. modifier onlyTbtcSystem(){ require(msg.sender == tbtcSystemAddress, "Caller must be tbtcSystem contract"); _; } } pragma solidity 0.5.17; /// @title Vending Machine Authority. /// @notice Contract to secure function calls to the Vending Machine. /// @dev Secured by setting the VendingMachine address and using the /// onlyVendingMachine modifier on functions requiring restriction. contract VendingMachineAuthority { address internal VendingMachine; constructor(address _vendingMachine) public { VendingMachine = _vendingMachine; } /// @notice Function modifier ensures modified function caller address is the vending machine. modifier onlyVendingMachine() { require(msg.sender == VendingMachine, "caller must be the vending machine"); _; } } pragma solidity 0.5.17; /// @title Interface of recipient contract for `approveAndCall` pattern. /// Implementors will be able to be used in an `approveAndCall` /// interaction with a supporting contract, such that a token approval /// can call the contract acting on that approval in a single /// transaction. /// /// See the `FundingScript` and `RedemptionScript` contracts as examples. interface ITokenRecipient { /// Typically called from a token contract's `approveAndCall` method, this /// method will receive the original owner of the token (`_from`), the /// transferred `_value` (in the case of an ERC721, the token id), the token /// address (`_token`), and a blob of `_extraData` that is informally /// specified by the implementor of this method as a way to communicate /// additional parameters. /// /// Token calls to `receiveApproval` should revert if `receiveApproval` /// reverts, and reverts should remove the approval. /// /// @param _from The original owner of the token approved for transfer. /// @param _value For an ERC20, the amount approved for transfer; for an /// ERC721, the id of the token approved for transfer. /// @param _token The address of the contract for the token whose transfer /// was approved. /// @param _extraData An additional data blob forwarded unmodified through /// `approveAndCall`, used to allow the token owner to pass /// additional parameters and data to this method. The structure of /// the extra data is informally specified by the implementor of /// this interface. function receiveApproval( address _from, uint256 _value, address _token, bytes calldata _extraData ) external; } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import "./VendingMachineAuthority.sol"; /// @title Fee Rebate Token /// @notice The Fee Rebate Token (FRT) is a non fungible token (ERC721) /// the ID of which corresponds to a given deposit address. /// If the corresponding deposit is still active, ownership of this token /// could result in reimbursement of the signer fee paid to open the deposit. /// @dev This token is minted automatically when a TDT (`TBTCDepositToken`) /// is exchanged for TBTC (`TBTCToken`) via the Vending Machine (`VendingMachine`). /// When the Deposit is redeemed, the TDT holder will be reimbursed /// the signer fee if the redeemer is not the TDT holder and Deposit is not /// at-term or in COURTESY_CALL. contract FeeRebateToken is ERC721Metadata, VendingMachineAuthority { constructor(address _vendingMachine) ERC721Metadata("tBTC Fee Rebate Token", "FRT") VendingMachineAuthority(_vendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token. /// @param _tokenId uint256 ID of the token to be minted. function mint(address _to, uint256 _tokenId) external onlyVendingMachine { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; /// @title ECDSA Keep /// @notice Contract reflecting an ECDSA keep. contract IBondedECDSAKeep { /// @notice Returns public key of this keep. /// @return Keeps's public key. function getPublicKey() external view returns (bytes memory); /// @notice Returns the amount of the keep's ETH bond in wei. /// @return The amount of the keep's ETH bond in wei. function checkBondAmount() external view returns (uint256); /// @notice Calculates a signature over provided digest by the keep. Note that /// signatures from the keep not explicitly requested by calling `sign` /// will be provable as fraud via `submitSignatureFraud`. /// @param _digest Digest to be signed. function sign(bytes32 _digest) external; /// @notice Distributes ETH reward evenly across keep signer beneficiaries. /// @dev Only the value passed to this function is distributed. function distributeETHReward() external payable; /// @notice Distributes ERC20 reward evenly across keep signer beneficiaries. /// @dev This works with any ERC20 token that implements a transferFrom /// function. /// This function only has authority over pre-approved /// token amount. We don't explicitly check for allowance, SafeMath /// subtraction overflow is enough protection. /// @param _tokenAddress Address of the ERC20 token to distribute. /// @param _value Amount of ERC20 token to distribute. function distributeERC20Reward(address _tokenAddress, uint256 _value) external; /// @notice Seizes the signers' ETH bonds. After seizing bonds keep is /// terminated so it will no longer respond to signing requests. Bonds can /// be seized only when there is no signing in progress or requested signing /// process has timed out. This function seizes all of signers' bonds. /// The application may decide to return part of bonds later after they are /// processed using returnPartialSignerBonds function. function seizeSignerBonds() external; /// @notice Returns partial signer's ETH bonds to the pool as an unbounded /// value. This function is called after bonds have been seized and processed /// by the privileged application after calling seizeSignerBonds function. /// It is entirely up to the application if a part of signers' bonds is /// returned. The application may decide for that but may also decide to /// seize bonds and do not return anything. function returnPartialSignerBonds() external payable; /// @notice Submits a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. /// @dev The function expects the signed digest to be calculated as a sha256 /// hash of the preimage: `sha256(_preimage)`. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, error otherwise. function submitSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes calldata _preimage ) external returns (bool _isFraud); /// @notice Closes keep when no longer needed. Releases bonds to the keep /// members. Keep can be closed only when there is no signing in progress or /// requested signing process has timed out. /// @dev The function can be called only by the owner of the keep and only /// if the keep has not been already closed. function closeKeep() external; } pragma solidity ^0.5.10; /** @title ValidateSPV*/ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; import {BTCUtils} from "./BTCUtils.sol"; library ValidateSPV { using BTCUtils for bytes; using BTCUtils for uint256; using BytesLib for bytes; using SafeMath for uint256; enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS } enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD } uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd; function getErrBadLength() internal pure returns (uint256) { return ERR_BAD_LENGTH; } function getErrInvalidChain() internal pure returns (uint256) { return ERR_INVALID_CHAIN; } function getErrLowWork() internal pure returns (uint256) { return ERR_LOW_WORK; } /// @notice Validates a tx inclusion in the block /// @dev `index` is not a reliable indicator of location within a block /// @param _txid The txid (LE) /// @param _merkleRoot The merkle root (as in the block header) /// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root) /// @param _index The leaf's index in the tree (0-indexed) /// @return true if fully valid, false otherwise function prove( bytes32 _txid, bytes32 _merkleRoot, bytes memory _intermediateNodes, uint _index ) internal pure returns (bool) { // Shortcut the empty-block case if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) { return true; } bytes memory _proof = abi.encodePacked(_txid, _intermediateNodes, _merkleRoot); // If the Merkle proof failed, bubble up error return _proof.verifyHash256Merkle(_index); } /// @notice Hashes transaction to get txid /// @dev Supports Legacy and Witness /// @param _version 4-bytes version /// @param _vin Raw bytes length-prefixed input vector /// @param _vout Raw bytes length-prefixed output vector /// @param _locktime 4-byte tx locktime /// @return 32-byte transaction id, little endian function calculateTxId( bytes memory _version, bytes memory _vin, bytes memory _vout, bytes memory _locktime ) internal pure returns (bytes32) { // Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime) return abi.encodePacked(_version, _vin, _vout, _locktime).hash256(); } /// @notice Checks validity of header chain /// @notice Compares the hash of each header to the prevHash in the next header /// @param _headers Raw byte array of header chain /// @return The total accumulated difficulty of the header chain, or an error code function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) { // Check header chain length if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;} // Initialize header start index bytes32 _digest; _totalDifficulty = 0; for (uint256 _start = 0; _start < _headers.length; _start += 80) { // ith header start index and ith header bytes memory _header = _headers.slice(_start, 80); // After the first header, check that headers are in a chain if (_start != 0) { if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;} } // ith header target uint256 _target = _header.extractTarget(); // Require that the header has sufficient work _digest = _header.hash256View(); if(uint256(_digest).reverseUint256() > _target) { return ERR_LOW_WORK; } // Add ith header difficulty to difficulty sum _totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty()); } } /// @notice Checks validity of header work /// @param _digest Header digest /// @param _target The target threshold /// @return true if header work is valid, false otherwise function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) { if (_digest == bytes32(0)) {return false;} return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target); } /// @notice Checks validity of header chain /// @dev Compares current header prevHash to previous header's digest /// @param _header The raw bytes header /// @param _prevHeaderDigest The previous header's digest /// @return true if the connect is valid, false otherwise function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) { // Extract prevHash of current header bytes32 _prevHash = _header.extractPrevBlockLE().toBytes32(); // Compare prevHash of current header to previous header's digest if (_prevHash != _prevHeaderDigest) {return false;} return true; } } pragma solidity ^0.5.10; /** @title CheckBitcoinSigs */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {BTCUtils} from "./BTCUtils.sol"; library CheckBitcoinSigs { using BytesLib for bytes; using BTCUtils for bytes; /// @notice Derives an Ethereum Account address from a pubkey /// @dev The address is the last 20 bytes of the keccak256 of the address /// @param _pubkey The public key X & Y. Unprefixed, as a 64-byte array /// @return The account address function accountFromPubkey(bytes memory _pubkey) internal pure returns (address) { require(_pubkey.length == 64, "Pubkey must be 64-byte raw, uncompressed key."); // keccak hash of uncompressed unprefixed pubkey bytes32 _digest = keccak256(_pubkey); return address(uint256(_digest)); } /// @notice Calculates the p2wpkh output script of a pubkey /// @dev Compresses keys to 33 bytes as required by Bitcoin /// @param _pubkey The public key, compressed or uncompressed /// @return The p2wkph output script function p2wpkhFromPubkey(bytes memory _pubkey) internal pure returns (bytes memory) { bytes memory _compressedPubkey; uint8 _prefix; if (_pubkey.length == 64) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(0, 32)); } else if (_pubkey.length == 65) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(1, 32)); } else { _compressedPubkey = _pubkey; } require(_compressedPubkey.length == 33, "Witness PKH requires compressed keys"); bytes memory _pubkeyHash = _compressedPubkey.hash160(); return abi.encodePacked(hex"0014", _pubkeyHash); } /// @notice checks a signed message's validity under a pubkey /// @dev does this using ecrecover because Ethereum has no soul /// @param _pubkey the public key to check (64 bytes) /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkSig( bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); address _expected = accountFromPubkey(_pubkey); address _actual = ecrecover(_digest, _v, _r, _s); return _actual == _expected; } /// @notice checks a signed message against a bitcoin p2wpkh output script /// @dev does this my verifying the p2wpkh matches an ethereum account /// @param _p2wpkhOutputScript the bitcoin output script /// @param _pubkey the uncompressed, unprefixed public key to check /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkBitcoinSig( bytes memory _p2wpkhOutputScript, bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer? if (!_isExpectedSigner) {return false;} bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s); return _sigResult; } /// @notice checks if a message is the sha256 preimage of a digest /// @dev this is NOT the hash256! this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isSha256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return sha256(_candidate) == _digest; } /// @notice checks if a message is the keccak256 preimage of a digest /// @dev this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isKeccak256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return keccak256(_candidate) == _digest; } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputScript the length-prefixed output script /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhSpendSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes memory _outputScript // lenght-prefixed output script ) internal pure returns (bytes32) { // Fixes elements to easily make a 1-in 1-out sighash digest // Does not support timelocks bytes memory _scriptCode = abi.encodePacked( hex"1976a914", // length, dup, hash160, pkh_length _inputPKH, hex"88ac"); // equal, checksig bytes32 _hashOutputs = abi.encodePacked( _outputValue, // 8-byte LE _outputScript).hash256(); bytes memory _sighashPreimage = abi.encodePacked( hex"01000000", // version _outpoint.hash256(), // hashPrevouts hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000) _outpoint, // outpoint _scriptCode, // p2wpkh script code _inputValue, // value of the input in 8-byte LE hex"00000000", // input nSequence _hashOutputs, // hash of the single output hex"00000000", // nLockTime hex"01000000" // SIGHASH_ALL ); return _sighashPreimage.hash256(); } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhToWpkhSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhSpendSighash( _outpoint, _inputPKH, _inputValue, _outputValue, abi.encodePacked( hex"160014", // wpkh tag _outputPKH) ); } /// @notice Preserved for API compatibility with older version /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function oneInputOneOutputSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either `approve` or `setApproveForAll`. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either `approve` or `setApproveForAll`. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity ^0.5.0; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "../../introspection/ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity ^0.5.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../drafts/Counters.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity ^0.5.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 { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * 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 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * 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.5.0; import "./IERC165.sol"; /** * @dev Implementation of the `IERC165` interface. * * Contracts may inherit from this and call `_registerInterface` to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See `IERC165.supportsInterface`. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See `IERC165.supportsInterface`. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } pragma solidity ^0.5.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); }
Convert a LE bytes8 to a uint256. Do this by converting to bytes, then reversing endianness, then converting to int. return The uint256 represented in LE by the bytes8.
function bytes8LEToUint(bytes8 _b) public pure returns (uint256) { return abi.encodePacked(_b).reverseEndianness().bytesToUint(); }
7,283,396
./full_match/1/0xC68a8c6A29412827018A23058E0CEd132889Ea48/sources/src/strategies/PancakeSwapPulseStrategyV2.sol
mutableParams_ structure with all mutable params of the strategy spotTick current spot tick of PancakeV3Pool of pancakeSwapVault pool PancakeV3Pool of pancakeSwapVault uniV3Nft Nft of PancakeSwap position return newInterval expected interval after reblance return neededNewInterval flag that is true if it is needed to mint new interval
function calculateNewPosition( MutableParams memory mutableParams_, int24 spotTick, IPancakeV3Pool pool, uint256 uniV3Nft ) public view returns (Interval memory newInterval, bool neededNewInterval) { int24 tickSpacing = pool.tickSpacing(); if (uniV3Nft == 0 || forceRebalanceWidthFlag) { return (formPositionWithSpotTickInCenter(mutableParams_, spotTick, tickSpacing), true); } Interval memory currentInterval; (, , , , , currentInterval.lowerTick, currentInterval.upperTick, , , , , ) = positionManager.positions( uniV3Nft ); int24 length = currentInterval.upperTick - currentInterval.lowerTick; int24 currentNeighborhood = int24( uint24(FullMath.mulDiv(uint24(length), mutableParams_.neighborhoodFactorD, D9)) ); int24 minAcceptableTick = currentInterval.lowerTick + currentNeighborhood; int24 maxAcceptableTick = currentInterval.upperTick - currentNeighborhood; if (minAcceptableTick <= spotTick && spotTick <= maxAcceptableTick) { return (currentInterval, false); } int24 closeness = minAcceptableTick - spotTick; if (spotTick - maxAcceptableTick > closeness) { closeness = spotTick - maxAcceptableTick; } int24 sideExtension = closeness + int24(int256(FullMath.mulDiv(uint24(currentNeighborhood), mutableParams_.extensionFactorD, D9))); if (sideExtension % tickSpacing != 0 || sideExtension == 0) { sideExtension += tickSpacing; sideExtension -= sideExtension % tickSpacing; } newInterval.lowerTick = currentInterval.lowerTick - sideExtension; newInterval.upperTick = currentInterval.upperTick + sideExtension; if (newInterval.upperTick - newInterval.lowerTick > mutableParams_.maxPositionLengthInTicks) { return (formPositionWithSpotTickInCenter(mutableParams_, spotTick, tickSpacing), true); } neededNewInterval = true; }
16,471,541
./full_match/421613/0xb63234AcaC10029EAebF63A0f28584cd096dF62B/sources/project_/contracts/GarbiMining.sol
Add a new pool. Can only be called by the owner.
function addPool(uint256 _allocPoint, IGarbiFarm _vegrbFarm) public onlyOwner { _validateTimelock(_timelock); require(_timelock.addressOf[keccak256(abi.encode('grabiFarm'))] == address(_vegrbFarm), 'INVALID_ADDRESS'); address want = address(_vegrbFarm.want()); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; poolInfo.push(PoolInfo({ want: want, grabiFarm: _vegrbFarm, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVeGRBPerShare: 0 })); delete _timelock.addressOf[keccak256(abi.encode('grabiFarm'))]; _timelock.queuedTransactions = false; }
11,566,609
./partial_match/1/0x4511E45687b0F18152A03C4FD20E61fb9B373431/sources/contracts/LOVProduct.sol
Permissionless method that reads price from oracle contracts and checks if barrier is triggered vaultAddress is address of the vault/
function checkBarriers(address vaultAddress) public onlyValidVault(vaultAddress) { FCNVaultMetadata storage vaultMetadata = vaults[vaultAddress]; vaultMetadata.checkBarriers(address(cegaState)); emit BarriersChecked(vaultAddress, vaultMetadata.isKnockedIn); }
3,626,792
./full_match/1/0x83797D8608aA53dFcC77D350081383dF021ee5Bc/sources/contracts/base/ERC721.sol
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./ Clear approvals from the previous owner
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); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId + _idShift); }
17,008,129
./partial_match/1/0xE02328fc277C355D20AF201d4b893A6790fC8766/sources/PEPEDREAM.sol
Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20Standard: transfer from the zero address"); require(to != address(0), "ERC20Standard: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20Standard: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
15,560,905
pragma solidity ^0.4.17; /** * V 1.0. * (C) profit-chain.net Licensed under MIT terms * * ProfitChain is a game allowing participants to win some Ether. Based on Ethereum intrinsic randomness and difficulty, you must be either lucky or one * hell of a hacker to win... Read the code, and if you find a problem, write owner AT profit-chain.net ! * * Investors participate in rounds of fixed size and investment. Once a round is full, a new one opens automatically. * A single winner is picked per round, raking all the round's investments (minus invitor fees). * * Each investor must provide an invitor address when making the first investment in the group. * The game includes a time and depth limited invitation pyramid - you must invest first, then you can invite others. As invitor you'll enjoy a part of invitees investment * and wins, as well as their sub-invitees, for a limited time, and up to certain number of generations. * * There are multiple groups, each with its specific characteristics- to cater to all players. * * We deter hacking of the winner by making it non-economical: * There is a "security factor" K, which is larger than the group round size N. * For example, for N=10 we may choose K=50. * A few blocks following the round's last investment, the winner is picked if the block's hash mod K is a number of 1...N. * If a hacker miner made a single invetment in the round, the miner would have to match 1 out of 50 "guesses", ie. 50 times greater effort than usual... * If a hacker miner made all invetments but one in the round, the miner would have to match 9 of of 50 "guesses", or about 5 times greater than usual... * And then there's the participation fees, that render even that last scenario non-economical. * * It would take a little over K blocks on average to declare the winner. * At 15 seconds per block, if K=50, it would take on average 13 minutes after the last investment, before a winner is found. * BUT! * Winner declaration is temporary - checking is done on last 255 blocks. So even if a winner exists now, the winner must be actively named using a transaction while relevant. * A "checkAndDeclareWinner" transaction is required to write the winner (at the time of the transaction!) into the blockchain. * * All Ether withdrawals, after wins or invitor fees payouts, require execution of a "withdraw" transaction, for safety. */ contract ProfitChain { using SafeMath256 for uint256; using SafeMath32 for uint32; // types struct Investment { address investor; // who made the investment uint256 sum; // actual investment, after fees deduction uint256 time; // investment time } struct Round { mapping(uint32 => Investment) investments; // all investments made in round mapping (address => uint32) investorMapping; // quickly find an investor by address uint32 totalInvestors; // the number of investors in round so far uint256 totalInvestment; // the sum of all investments in round, so far address winner; // winner of the round (0 if not yet known) uint256 lastBlock; // block number of latest investment } struct GroupMember { uint256 joinTime; // when the pariticipant joined the group address invitor; // who invited the participant } struct Group { string name; // group name uint32 roundSize; // round size (number of investors) uint256 investment; // investment size in wei uint32 blocksBeforeWinCheck; // how many blocks to wait after round's final investment, prior to determining the winner uint32 securityFactor; // security factor, larger than the group size, to make hacking difficult uint32 invitationFee; // promiles of invitation fee out of investment and winning uint32 ownerFee; // promiles of owner fee out of investment uint32 invitationFeePeriod; // number of days an invitation incurs fees uint8 invitationFeeDepth; // how many invitors can be paid up the invitation chain bool active; // is the group open for new rounds? mapping (address => GroupMember) members; // all the group members mapping(uint32 => Round) rounds; // rounds of this group uint32 currentRound; // the current round uint32 firstUnwonRound; // the oldest round we need to check for win } // variables string public contractName = "ProfitChain 1.0"; uint256 public contractBlock; // block of contract address public owner; // owner of the contract mapping (address => uint256) balances; // balance of each investor Group[] groups; // all groups mapping (string => bool) groupNames; // for exclusivity of group names // modifiers modifier onlyOwner() {require(msg.sender == owner); _;} // events event GroupCreated(uint32 indexed group, uint256 timestamp); event GroupClosed(uint32 indexed group, uint256 timestamp); event NewInvestor(address indexed investor, uint32 indexed group, uint256 timestamp); event Invest(address indexed investor, uint32 indexed group, uint32 indexed round, uint256 timestamp); event Winner(address indexed payee, uint32 indexed group, uint32 indexed round, uint256 timestamp); event Deposit(address indexed payee, uint256 sum, uint256 timestamp); event Withdraw(address indexed payee, uint256 sum, uint256 timestamp); // functions /** * Constructor: * - owner account */ function ProfitChain () public { owner = msg.sender; contractBlock = block.number; } /** * if someones sends Ether directly to the contract - fail it! */ function /* fallback */ () public payable { revert(); } /** * Create new group (only owner) */ function newGroup ( string _groupName, uint32 _roundSize, uint256 _investment, uint32 _blocksBeforeWinCheck, uint32 _securityFactor, uint32 _invitationFee, uint32 _ownerFee, uint32 _invitationFeePeriod, uint8 _invitationFeeDepth ) public onlyOwner { // some basic tests require(_roundSize > 0); require(_investment > 0); require(_invitationFee.add(_ownerFee) < 1000); require(_securityFactor > _roundSize); // check if group name exists require(!groupNameExists(_groupName)); // create the group Group memory group; group.name = _groupName; group.roundSize = _roundSize; group.investment = _investment; group.blocksBeforeWinCheck = _blocksBeforeWinCheck; group.securityFactor = _securityFactor; group.invitationFee = _invitationFee; group.ownerFee = _ownerFee; group.invitationFeePeriod = _invitationFeePeriod; group.invitationFeeDepth = _invitationFeeDepth; group.active = true; // group.currentRound = 0; // initialized with 0 anyway // group.firstUnwonRound = 0; // initialized with 0 anyway groups.push(group); groupNames[_groupName] = true; // notify world GroupCreated(uint32(groups.length).sub(1), block.timestamp); } /** * Close group (only owner) * Once closed, it will not initiate new rounds. */ function closeGroup(uint32 _group) onlyOwner public { // verify group exists and not closed require(groupExists(_group)); require(groups[_group].active); groups[_group].active = false; // notify the world GroupClosed(_group, block.timestamp); } /** * Join group and make first investment * Invitor must already belong to group (or be owner), investor must not. */ function joinGroupAndInvest(uint32 _group, address _invitor) payable public { address investor = msg.sender; // owner is not allowed to invest require(msg.sender != owner); // check group exists, investor does not yet belong to group, and invitor exists (or owner) Group storage thisGroup = groups[_group]; require(thisGroup.roundSize > 0); require(thisGroup.members[_invitor].joinTime > 0 || _invitor == owner); require(thisGroup.members[investor].joinTime == 0); // check payment is as required require(msg.value == thisGroup.investment); // add investor to group thisGroup.members[investor].joinTime = block.timestamp; thisGroup.members[investor].invitor = _invitor; // notify the world NewInvestor(investor, _group, block.timestamp); // make the first investment invest(_group); } /** * Invest in a group * Can invest once per round. * Must be a member of the group. */ function invest(uint32 _group) payable public { address investor = msg.sender; Group storage thisGroup = groups[_group]; uint32 round = thisGroup.currentRound; Round storage thisRound = thisGroup.rounds[round]; // check the group is still open for business - only if we're about to be the first investors require(thisGroup.active || thisRound.totalInvestors > 0); // check payment is as required require(msg.value == thisGroup.investment); // verify we're members require(thisGroup.members[investor].joinTime > 0); // verify we're not already investors in this round require(! isInvestorInRound(thisRound, investor)); // notify the world Invest(investor, _group, round, block.timestamp); // calculate fees. there are owner fee and invitor fee uint256 ownerFee = msg.value.mul(thisGroup.ownerFee).div(1000); balances[owner] = balances[owner].add(ownerFee); Deposit(owner, ownerFee, block.timestamp); uint256 investedSumLessOwnerFee = msg.value.sub(ownerFee); uint256 invitationFee = payAllInvitors(thisGroup, investor, block.timestamp, investedSumLessOwnerFee, 0); uint256 investedNetSum = investedSumLessOwnerFee.sub(invitationFee); // join the round thisRound.investorMapping[investor] = thisRound.totalInvestors; thisRound.investments[thisRound.totalInvestors] = Investment({ investor: investor, sum: investedNetSum, time: block.timestamp}); thisRound.totalInvestors = thisRound.totalInvestors.add(1); thisRound.totalInvestment = thisRound.totalInvestment.add(investedNetSum); // check if this round has been completely populated. If so, close this round and prepare the next round if (thisRound.totalInvestors == thisGroup.roundSize) { thisGroup.currentRound = thisGroup.currentRound.add(1); thisRound.lastBlock = block.number; } // every investor also helps by checking for a previous winner. address winner; string memory reason; (winner, reason) = checkWinnerInternal(thisGroup); if (winner != 0) declareWinner(_group, winner); } /** * withdraw collects due funds in a safe manner */ function withdraw(uint256 sum) public { address withdrawer = msg.sender; // do we have enough funds for withdrawal? require(balances[withdrawer] >= sum); // notify the world Withdraw(withdrawer, sum, block.timestamp); // update (safely) balances[withdrawer] = balances[withdrawer].sub(sum); withdrawer.transfer(sum); } /** * checkWinner checks if at the time of the call a winner exists for the currently earliest unwon round of the given group. * No declaration is made - so another winner could be selected later! */ function checkWinner(uint32 _group) public constant returns (bool foundWinner, string reason) { Group storage thisGroup = groups[_group]; require(thisGroup.roundSize > 0); address winner; (winner, reason) = checkWinnerInternal(thisGroup); foundWinner = winner != 0; } /** * checkAndDeclareWinner checks if at the time of the call a winner exists for the currently earliest unwon round of the given group, * and then declares the winner. * Reverts if no winner found, to prevent unnecessary gas expenses. */ function checkAndDeclareWinner(uint32 _group) public { Group storage thisGroup = groups[_group]; require(thisGroup.roundSize > 0); address winner; string memory reason; (winner, reason) = checkWinnerInternal(thisGroup); // revert if no winner found require(winner != 0); // let's declare the winner! declareWinner(_group, winner); } /** * declareWinner etches the winner into the blockchain. */ function declareWinner(uint32 _group, address _winner) internal { // let's declare the winner! Group storage thisGroup = groups[_group]; Round storage unwonRound = thisGroup.rounds[thisGroup.firstUnwonRound]; unwonRound.winner = _winner; // notify the world Winner(_winner, _group, thisGroup.firstUnwonRound, block.timestamp); uint256 wonSum = unwonRound.totalInvestment; wonSum = wonSum.sub(payAllInvitors(thisGroup, _winner, block.timestamp, wonSum, 0)); balances[_winner] = balances[_winner].add(wonSum); Deposit(_winner, wonSum, block.timestamp); // update the unwon round thisGroup.firstUnwonRound = thisGroup.firstUnwonRound.add(1); } /** * checkWinnerInernal tries finding a winner for the oldest non-decided round. * Returns winner != 0 iff a new winner was found, as well as reason */ function checkWinnerInternal(Group storage thisGroup) internal constant returns (address winner, string reason) { winner = 0; // assume have not found a new winner // some tests // the first round has no previous rounds to check if (thisGroup.currentRound == 0) { reason = 'Still in first round'; return; } // we don't check current round - by definition it is not full if (thisGroup.currentRound == thisGroup.firstUnwonRound) { reason = 'No unwon finished rounds'; return; } Round storage unwonRound = thisGroup.rounds[thisGroup.firstUnwonRound]; // we will scan a range of blocks, from unwonRound.lastBlock + thisGroup.blocksBeforeWinCheck; uint256 firstBlock = unwonRound.lastBlock.add(thisGroup.blocksBeforeWinCheck); // but we can't scan more than 255 blocks into the past // the first test is for testing environments that may have less than 256 blocks :) if (block.number > 255 && firstBlock < block.number.sub(255)) firstBlock = block.number.sub(255); // the scan ends at the last committed block uint256 lastBlock = block.number.sub(1); for (uint256 thisBlock = firstBlock; thisBlock <= lastBlock; thisBlock = thisBlock.add(1)) { uint256 latestHash = uint256(block.blockhash(thisBlock)); // we're "drawing" a winner out of the security-factor-sized group - perhaps no winner at all uint32 drawn = uint32(latestHash % thisGroup.securityFactor); if (drawn < thisGroup.roundSize) { // we have a winner! winner = unwonRound.investments[drawn].investor; return; } } reason = 'No winner picked'; } /** * Given a group, investor and amount of wei, pay all the eligible invitors. * NOTE: does not draw from the _payer balance - we're assuming the returned value will be deducted when necessary. * NOTE 2: a recursive call, yet the depth is limited by 8-bits so no real stack concren. * Return the amount of wei to be deducted from the payer */ function payAllInvitors(Group storage thisGroup, address _payer, uint256 _relevantTime, uint256 _amount, uint32 _depth) internal returns (uint256 invitationFee) { address invitor = thisGroup.members[_payer].invitor; // conditions for payment: if ( // the payer's invitor is not the owner... invitor == owner || // must have something to share... _amount == 0 || // no more than specified depth _depth >= thisGroup.invitationFeeDepth || // the invitor's invitation time has not expired _relevantTime > thisGroup.members[_payer].joinTime.add(thisGroup.invitationFeePeriod.mul(1 days)) ) { return; } // compute how much to pay invitationFee = _amount.mul(thisGroup.invitationFee).div(1000); // we may have reached rock bottom - don't continue if (invitationFee == 0) return; // calculate recursively even higher-hierarcy fees uint256 invitorFee = payAllInvitors(thisGroup, invitor, _relevantTime, invitationFee, _depth.add(1)); // out net invitation fees are... uint256 paid = invitationFee.sub(invitorFee); // pay balances[invitor] = balances[invitor].add(paid); // notify the world Deposit(invitor, paid, block.timestamp); } /** * Is a specific investor in a specific round? */ function isInvestorInRound(Round storage _round, address _investor) internal constant returns (bool investorInRound) { return (_round.investments[_round.investorMapping[_investor]].investor == _investor); } /** * Get info about specific account */ function balanceOf(address investor) public constant returns (uint256 balance) { balance = balances[investor]; } /** * Get info about groups */ function groupsCount() public constant returns (uint256 count) { count = groups.length; } /** * Get info about specific group */ function groupInfo(uint32 _group) public constant returns ( string name, uint32 roundSize, uint256 investment, uint32 blocksBeforeWinCheck, uint32 securityFactor, uint32 invitationFee, uint32 ownerFee, uint32 invitationFeePeriod, uint8 invitationFeeDepth, bool active, uint32 currentRound, uint32 firstUnwonRound ) { require(groupExists(_group)); Group storage thisGroup = groups[_group]; name = thisGroup.name; roundSize = thisGroup.roundSize; investment = thisGroup.investment; blocksBeforeWinCheck = thisGroup.blocksBeforeWinCheck; securityFactor = thisGroup.securityFactor; invitationFee = thisGroup.invitationFee; ownerFee = thisGroup.ownerFee; invitationFeePeriod = thisGroup.invitationFeePeriod; invitationFeeDepth = thisGroup.invitationFeeDepth; active = thisGroup.active; currentRound = thisGroup.currentRound; firstUnwonRound = thisGroup.firstUnwonRound; } /** * Get info about specific group member */ function groupMemberInfo (uint32 _group, address investor) public constant returns ( uint256 joinTime, address invitor ) { require(groupExists(_group)); GroupMember storage groupMember = groups[_group].members[investor]; joinTime = groupMember.joinTime; invitor = groupMember.invitor; } /** * Get info about specific group's round */ function roundInfo (uint32 _group, uint32 _round) public constant returns ( uint32 totalInvestors, uint256 totalInvestment, address winner, uint256 lastBlock ) { require(groupExists(_group)); Round storage round = groups[_group].rounds[_round]; totalInvestors = round.totalInvestors; totalInvestment = round.totalInvestment; winner = round.winner; lastBlock = round.lastBlock; } /** * Get info about specific round's investment, by investor */ function roundInvestorInfoByAddress (uint32 _group, uint32 _round, address investor) public constant returns ( bool inRound, uint32 index ) { require(groupExists(_group)); index = groups[_group].rounds[_round].investorMapping[investor]; inRound = isInvestorInRound(groups[_group].rounds[_round], investor); } /** * Get info about specific round's investment - by index */ function roundInvestorInfoByIndex (uint32 _group, uint32 _round, uint32 _index) public constant returns ( address investor, uint256 sum, uint256 time ) { require(groupExists(_group)); require(groups[_group].rounds[_round].totalInvestors > _index); Investment storage investment = groups[_group].rounds[_round].investments[_index]; investor = investment.investor; sum = investment.sum; time = investment.time; } /** * Does group name exist? */ function groupNameExists(string _groupName) internal constant returns (bool exists) { return groupNames[_groupName]; } function groupExists(uint32 _group) internal constant returns (bool exists) { return _group < groups.length; } } library SafeMath256 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } library SafeMath32 { function mul(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint32 a, uint32 b) internal pure returns (uint32) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint32 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint32 a, uint32 b) internal pure returns (uint32) { require(b <= a); return a - b; } function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a); return c; } }
Is a specific investor in a specific round?/
function isInvestorInRound(Round storage _round, address _investor) internal constant returns (bool investorInRound) { return (_round.investments[_round.investorMapping[_investor]].investor == _investor); }
6,450,628
/// @author Jianwei Liu [email protected] pragma solidity 0.5.12; import {Ownable} from "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** @notice The VaultNotary contract is the contract for reading/writing the * vault uri and hash, and controlling the permissions to those operations by vault * owner. */ contract VaultNotary is Ownable { struct Data { /* Struct Slot 0 */ // The access control mapping to record whether an address can update the Hash of a Vault mapping(address => bool) hashAcl; /* Struct Slot 1 */ // The access control mapping to record whether an address can update the Uri of a Vault mapping(address => bool) uriAcl; /* Struct Slot 2 */ // The address of the Vault owner, 20 bytes address vaultOwner; /* Struct Slot 3 */ string vaultHash; /* Struct Slot 4 */ string vaultUri; } /* Slot 0, data part at keccak256(key . uint256(0)), where . is concatenation*/ // Each Vault has its own Data mapping(bytes16 => VaultNotary.Data) internal notaryMapping; /* Slot 1 */ // Boolean that controls whether this contract is deprecated or not, 1 byte bool internal isDeprecated; // Notary Events event VaultUri(address indexed msgSender, bytes16 indexed vaultId, string vaultUri); event VaultHash(address indexed msgSender, bytes16 indexed vaultId, string vaultHash); event VaultRegistered(address indexed msgSender, bytes16 indexed vaultId); event UpdateHashPermissionGranted(address indexed msgSender, bytes16 indexed vaultId, address indexed addressToGrant); event UpdateHashPermissionRevoked(address indexed msgSender, bytes16 indexed vaultId, address indexed addressToRevoke); event UpdateUriPermissionGranted(address indexed msgSender, bytes16 indexed vaultId, address indexed addressToGrant); event UpdateUriPermissionRevoked(address indexed msgSender, bytes16 indexed vaultId, address indexed addressToRevoke); // Contract Events event ContractDeprecatedSet(address indexed msgSender, bool isDeprecated); /** @dev Modifier for limiting the access to vaultUri update * only whitelisted user can do the decorated operation */ modifier canUpdateUri(bytes16 vaultId) { require(msg.sender == notaryMapping[vaultId].vaultOwner || notaryMapping[vaultId].uriAcl[msg.sender], "Only the vault owner or whitelisted users can update vault URI"); _; } /** @dev Modifier for limiting the access to vaultHash update * only whitelisted user can do the decorated operation */ modifier canUpdateHash(bytes16 vaultId) { require(msg.sender == notaryMapping[vaultId].vaultOwner || notaryMapping[vaultId].hashAcl[msg.sender], "Only the vault owner or whitelisted users can update vault hash"); _; } /** @dev Modifier for limiting the access to grant and revoke permissions * Will check the message sender, only the owner of a vault can do the operation decorated * @param vaultId bytes16 ID of the vault to check */ modifier vaultOwnerOnly(bytes16 vaultId) { require(msg.sender == notaryMapping[vaultId].vaultOwner, "Method only accessible to vault owner"); _; } /** @notice This modifier is for testing whether a Vault has been registered yet * @param vaultId bytes16 The ID of the vault to check */ modifier isNotRegistered(bytes16 vaultId) { require(notaryMapping[vaultId].vaultOwner == address(0x0), "Vault ID already exists"); _; } /** @notice This modifier is for testing whether a Vault has been registered yet * @param vaultId bytes16 The ID of the vault to check */ modifier isRegistered(bytes16 vaultId) { require(notaryMapping[vaultId].vaultOwner != address(0x0), "Vault ID does not exist"); _; } /** @notice If we upgrade the version of the contract, the old contract * will not be allowed to register new Vault anymore. However, the existing * Vaults registered in that contract should still be able to be updated */ modifier notDeprecated() { require(!isDeprecated, "This version of the VaultNotary contract has been deprecated"); _; } /** @notice This is function to register a vault, will only do the registration if a vaultId has not been registered before * @dev It sets the msg.sender to the vault owner, and calls the setVaultUri and setVaultHash to * initialize the uri and hash of a vault. It emits VaultRegistered on success. * @param vaultId bytes16 VaultID to create, is the same as shipment ID in our system * @param vaultUri string Vault URI to set * @param vaultHash string Vault hash to set */ function registerVault(bytes16 vaultId, string calldata vaultUri, string calldata vaultHash) external notDeprecated isNotRegistered(vaultId) { notaryMapping[vaultId].vaultOwner = msg.sender; //work around for if (vaultUri != "") if (bytes(vaultUri).length != 0) setVaultUri(vaultId, vaultUri); if (bytes(vaultHash).length != 0) setVaultHash(vaultId, vaultHash); emit VaultRegistered(msg.sender, vaultId); } /** @notice Sets the contract isDeprecated flag. Vault registration will be disabled if isDeprecated == True * Only contract owner can set this * @dev It emits ContractDeprecatedSet on success * @param _isDeprecated bool Boolean control variable */ function setDeprecated(bool _isDeprecated) external onlyOwner { isDeprecated = _isDeprecated; emit ContractDeprecatedSet(msg.sender, isDeprecated); } /** @notice Function to grant update permission to the hash field in a vault * @dev It emits UpdateHashPermissionGranted on success * @param vaultId bytes16 The ID of Vault to grant permission * @param addressToGrant address The address to grant permission */ function grantUpdateHashPermission(bytes16 vaultId, address addressToGrant) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].hashAcl[addressToGrant] = true; emit UpdateHashPermissionGranted(msg.sender, vaultId, addressToGrant); } /** @notice Function to revoke update permission to the hash field in a vault * @dev It emits UpdateHashPermissionRevoked on success * @param vaultId The ID of Vault to revoke permission * @param addressToRevoke address The address to revoke permission */ function revokeUpdateHashPermission(bytes16 vaultId, address addressToRevoke) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].hashAcl[addressToRevoke] = false; emit UpdateHashPermissionRevoked(msg.sender, vaultId, addressToRevoke); } /** @notice Function to grant update permission to the Uri field in a vault * @dev It emits UpdateUriPermissionGranted on success * @param vaultId bytes16 The ID of Vault to grant permission * @param addressToGrant address The address to grant permission */ function grantUpdateUriPermission(bytes16 vaultId, address addressToGrant) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].uriAcl[addressToGrant] = true; emit UpdateUriPermissionGranted(msg.sender, vaultId, addressToGrant); } /** @notice Function to revoke update permission to the Uri field in a vault * @dev It emits UpdateUriPermissionRevoked on success * @param vaultId The ID of Vault to revoke permission * @param addressToRevoke address The address to revoke permission */ function revokeUpdateUriPermission(bytes16 vaultId, address addressToRevoke) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].uriAcl[addressToRevoke] = false; emit UpdateUriPermissionRevoked(msg.sender, vaultId, addressToRevoke); } /** @notice This function can read the vaultUri, vaultHash and vaultOwner given a * vaultId. It can be used in unit tests to verify the values are correct * after calling registerVault or using the setters. It can also be used * by outside users to read the details of a vault. If vaultID is not * registered, the vaultOwner returned will be 0x0. Otherwise, vaultOwner will * not be 0x0. Therefore, the returned vaultOwner can be used to test whether * the queried vault is registered. When vault not registered, the returned * vaultUri and vaultHash will both be empty strings * @param vaultId bytes16 The ID of the Vault to query * @return vaultUri string The uri of the vault * @return vaultHash string The hash of the vault * @return vaultOwner address The address of the vault owner */ function getVaultNotaryDetails(bytes16 vaultId) external view returns(string memory vaultUri, string memory vaultHash, address vaultOwner) { vaultUri = notaryMapping[vaultId].vaultUri; vaultHash = notaryMapping[vaultId].vaultHash; vaultOwner = notaryMapping[vaultId].vaultOwner; } /** @notice Function to set the vault URI * @dev It emits VaultUri on success * @param vaultId bytes16 ID of the vault to set * @param vaultUri string The vault URI to set */ function setVaultUri(bytes16 vaultId, string memory vaultUri) public isRegistered(vaultId) canUpdateUri(vaultId) { notaryMapping[vaultId].vaultUri = vaultUri; emit VaultUri(msg.sender, vaultId, vaultUri); } /** @notice Function to set the vault hash * @dev It emits VaultHash on success * @param vaultId bytes16 ID of the vault to set * @param vaultHash string The vault hash to set */ function setVaultHash(bytes16 vaultId, string memory vaultHash) public isRegistered(vaultId) canUpdateHash(vaultId) { notaryMapping[vaultId].vaultHash = vaultHash; emit VaultHash(msg.sender, vaultId, vaultHash); } }
Function to grant update permission to the hash field in a vault It emits UpdateHashPermissionGranted on success vaultId bytes16 The ID of Vault to grant permission addressToGrant address The address to grant permission/
function grantUpdateHashPermission(bytes16 vaultId, address addressToGrant) external isRegistered(vaultId) vaultOwnerOnly(vaultId) { notaryMapping[vaultId].hashAcl[addressToGrant] = true; emit UpdateHashPermissionGranted(msg.sender, vaultId, addressToGrant); }
2,520,328
./full_match/1/0x0c6dFD9B2f0bB08e52BCc0C20fE4c4957Fb58f3E/sources/project_/contracts/DioneStaking.sol
Internal Function - User normal withdraw _user User address
function _withdraw(address _user) internal { UserInfo storage user = userInfo[_user]; uint256 _pendingPenalty = user.amount.mul(accPenaltyPerShare).div(PRECISION_FACTOR).sub(user.penaltyDebt).add(user.penaltyClaimable); uint256 _pendingReward = _getUserPendingReward(_user); if(user.stakingTimestamp + REWARD_PERIOD >= stakingEndTime) { _pendingPenalty = 0; user.reimbursementAmount = 0; } uint256 _amount = user.amount.add(user.reimbursementAmount).add(_pendingPenalty).add(_pendingReward); _initializeUser(_user, false); user.rewardClaimed = user.rewardClaimed.add(_pendingReward); dione.safeTransfer(burnAddress, _amount); emit Withdraw(_user, _amount); }
4,872,858
./full_match/43114/0x23BECb8A22D3C6978F1A04b891262C832f5Ef3D2/sources/contracts/ERC20.sol
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 antiWhale(_msgSender(), recipient, amount) returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
4,535,623
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @dev TestGhostMarketERC721_V2 for upgrade. */ import "../contracts/ERC721PresetMinterPauserAutoIdUpgradeableCustom.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol"; contract TestGhostMarketERC721_V2 is Initializable, ERC721PresetMinterPauserAutoIdUpgradeableCustom, ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC165StorageUpgradeable { // struct for royalties fees struct Royalty { address payable recipient; uint256 value; } // tokenId => royalties array mapping(uint256 => Royalty[]) internal _royalties; // tokenId => locked content array mapping(uint256 => string) internal _lockedContent; // tokenId => locked content view counter array mapping(uint256 => uint256) internal _lockedContentViewTracker; // tokenId => attributes array mapping(uint256 => string) internal _metadataJson; // events event LockedContentViewed(address msgSender, uint256 tokenId, string lockedContent); event MintFeesWithdrawn(address feeWithdrawer, uint256 withdrawAmount); event MintFeesUpdated(address feeUpdater, uint256 newValue); event Minted(address toAddress, uint256 tokenId, string externalURI); event NewMintFeeIncremented(uint256 newValue); // mint fees balance uint256 internal _payedMintFeesBalance; // mint fees value uint256 internal _ghostmarketMintFees; /** * bytes4(keccak256(_INTERFACE_ID_ERC721_GHOSTMARKET)) == 0xee40ffc1 */ bytes4 private constant _INTERFACE_ID_ERC721_GHOSTMARKET = 0xee40ffc1; function initialize(string memory name, string memory symbol, string memory uri) public override initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC721Enumerable_init_unchained(); __ERC721Burnable_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); __ERC721URIStorage_init_unchained(); __ERC721_init_unchained(name, symbol); __ERC721PresetMinterPauserAutoId_init_unchained(uri); __Ownable_init_unchained(); _registerInterface(_INTERFACE_ID_ERC721_GHOSTMARKET); } function getSomething() external pure returns (uint) { return 10; } function incrementMintingFee() external { _ghostmarketMintFees2 = _ghostmarketMintFees + 1; emit NewMintFeeIncremented(_ghostmarketMintFees2); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721PresetMinterPauserAutoIdUpgradeableCustom, ERC165StorageUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev set a NFT royalties fees & recipients * fee basis points 10000 = 100% */ function _saveRoyalties(uint256 tokenId, Royalty[] memory royalties) internal { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); for (uint256 i = 0; i < royalties.length; i++) { require(royalties[i].recipient != address(0x0), "Recipient should be present"); require(royalties[i].value > 0, "Royalties value should be positive"); require(royalties[i].value <= 5000, "Royalties value should not be more than 50%"); _royalties[tokenId].push(royalties[i]); } } /** * @dev set a NFT custom attributes to contract storage */ function _setMetadataJson(uint256 tokenId, string memory metadataJson) internal { _metadataJson[tokenId] = metadataJson; } /** * @dev set a NFT locked content as string */ function _setLockedContent(uint256 tokenId, string memory content) internal { _lockedContent[tokenId] = content; } /** * @dev check mint fees sent to contract * emits MintFeesPaid event if set */ function _checkMintFees() internal { if (_ghostmarketMintFees > 0) { require(msg.value == _ghostmarketMintFees, "Wrong fees value sent to GhostMarket for mint fees"); } if (msg.value > 0) { _payedMintFeesBalance += msg.value; } } /** * @dev increment a NFT locked content view tracker */ function _incrementCurrentLockedContentViewTracker(uint256 tokenId) internal { _lockedContentViewTracker[tokenId] = _lockedContentViewTracker[tokenId] + 1; } /** * @dev mint NFT, set royalties, set metadata json, set lockedcontent * emits Minted event */ function mintGhost(address to, Royalty[] memory royalties, string memory externalURI, string memory metadata, string memory lockedcontent) external payable nonReentrant { require(to != address(0x0), "to can't be empty"); require(keccak256(abi.encodePacked(externalURI)) != keccak256(abi.encodePacked("")), "externalURI can't be empty"); mint(to); uint256 tokenId = getLastTokenID(); if (royalties.length > 0) { _saveRoyalties(tokenId, royalties); } if (keccak256(abi.encodePacked(metadata)) != keccak256(abi.encodePacked(""))) { _setMetadataJson(tokenId, metadata); } if (keccak256(abi.encodePacked(lockedcontent)) != keccak256(abi.encodePacked(""))) { _setLockedContent(tokenId, lockedcontent); } _checkMintFees(); emit Minted(to, tokenId, externalURI); } /** * @dev withdraw contract balance * emits MintFeesWithdrawn event */ function withdraw(uint256 withdrawAmount) external onlyOwner { require(withdrawAmount > 0 && withdrawAmount <= _payedMintFeesBalance, "Withdraw amount should be greater then 0 and less then contract balance"); _payedMintFeesBalance -= withdrawAmount; (bool success, ) = msg.sender.call{value: withdrawAmount}(""); require(success, "Transfer failed."); emit MintFeesWithdrawn(msg.sender, withdrawAmount); } /** * @dev bulk burn NFT */ function burnBatch(uint256[] memory tokensId) external { for (uint256 i = 0; i < tokensId.length; i++) { burn(tokensId[i]); } } /** * @dev sets Ghostmarket mint fees as uint256 * emits MintFeesUpdated event */ function setGhostmarketMintFee(uint256 gmmf) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller must have admin role to set mint fees"); _ghostmarketMintFees = gmmf; emit MintFeesUpdated(msg.sender, _ghostmarketMintFees); } /** * @return get Ghostmarket mint fees */ function getGhostmarketMintFees() external view returns (uint256) { return _ghostmarketMintFees; } /** * @dev get locked content for a NFT * emits LockedContentViewed event */ function getLockedContent(uint256 tokenId) external { require(ownerOf(tokenId) == msg.sender, "Caller must be the owner of the NFT"); _incrementCurrentLockedContentViewTracker(tokenId); emit LockedContentViewed(msg.sender, tokenId, _lockedContent[tokenId]); } /** * @dev get a NFT current locked content view tracker */ function getCurrentLockedContentViewTracker(uint256 tokenId) external view returns (uint256) { return _lockedContentViewTracker[tokenId]; } /** * @dev get a NFT custom attributes */ function getMetadataJson(uint256 tokenId) external view returns (string memory) { return _metadataJson[tokenId]; } /** * @dev get a NFT royalties recipients */ function getRoyaltiesRecipients(uint256 tokenId) external view returns (address payable[] memory) { Royalty[] memory royalties = _royalties[tokenId]; address payable[] memory result = new address payable[](royalties.length); for (uint256 i = 0; i < royalties.length; i++) { result[i] = royalties[i].recipient; } return result; } /** * @dev get a NFT royalties fees * fee basis points 10000 = 100% */ function getRoyaltiesBps(uint256 tokenId) external view returns (uint256[] memory) { Royalty[] memory royalties = _royalties[tokenId]; uint256[] memory result = new uint256[](royalties.length); for (uint256 i = 0; i < royalties.length; i++) { result[i] = royalties[i].value; } return result; } uint256[50] private __gap; uint256 internal _ghostmarketMintFees2; }
increment a NFT locked content view tracker/
function _incrementCurrentLockedContentViewTracker(uint256 tokenId) internal { _lockedContentViewTracker[tokenId] = _lockedContentViewTracker[tokenId] + 1; }
1,777,554
./full_match/5/0x0Bd4CC84A6cEec6De829422D81A08d53dbBCb786/sources/contracts/Dcolab.sol
? A check to ensure the project exists
function checkProjectID(uint256 _projectID) internal view { require(_projectID < allProjects.length, "This project does not exist"); }
1,880,082
./partial_match/80001/0x94086f81367Ec9398665D9b66d299510EE3Ce57B/sources/contracts/AlgebraFactory.sol
@inheritdoc IAlgebraFactory
function createPool(address tokenA, address tokenB) external override returns (address pool) { require(tokenA != tokenB); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0)); require(poolByPair[token0][token1] == address(0)); address defaultPlugin; if (address(defaultPluginFactory) != address(0)) { defaultPlugin = defaultPluginFactory.createPlugin(computePoolAddress(token0, token1)); } pool = IAlgebraPoolDeployer(poolDeployer).deploy(defaultPlugin, token0, token1); poolByPair[token1][token0] = pool; emit Pool(token0, token1, pool); }
8,804,947
pragma solidity 0.7.1; pragma experimental ABIEncoderV2; contract CoreUniLotterySettings { // Percentage calculations. // As Solidity doesn't have floats, we have to use integers for // percentage arithmetics. // We set 1 percent to be equal to 1,000,000 - thus, we // simulate 6 decimal points when computing percentages. uint32 public constant PERCENT = 10 ** 6; uint32 constant BASIS_POINT = PERCENT / 100; uint32 constant _100PERCENT = 100 * PERCENT; /** The UniLottery Owner's address. * * In the current version, The Owner has rights to: * - Take up to 10% profit from every lottery. * - Pool liquidity into the pool and unpool it. * - Start new Auto-Mode & Manual-Mode lotteries. * - Set randomness provider gas price & other settings. */ // Public Testnets: 0xb13CB9BECcB034392F4c9Db44E23C3Fb5fd5dc63 // MainNet: 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 address payable public constant OWNER_ADDRESS = address( uint160( 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 ) ); // Maximum lottery fee the owner can imburse on transfers. uint32 constant MAX_OWNER_LOTTERY_FEE = 1 * PERCENT; // Minimum amout of profit percentage that must be distributed // to lottery winners. uint32 constant MIN_WINNER_PROFIT_SHARE = 40 * PERCENT; // Min & max profits the owner can take from lottery net profit. uint32 constant MIN_OWNER_PROFITS = 3 * PERCENT; uint32 constant MAX_OWNER_PROFITS = 10 * PERCENT; // Min & max amount of lottery profits that the pool must get. uint32 constant MIN_POOL_PROFITS = 10 * PERCENT; uint32 constant MAX_POOL_PROFITS = 60 * PERCENT; // Maximum lifetime of a lottery - 1 month (4 weeks). uint32 constant MAX_LOTTERY_LIFETIME = 4 weeks; // Callback gas requirements for a lottery's ending callback, // and for the Pool's Scheduled Callback. // Must be determined empirically. uint32 constant LOTTERY_RAND_CALLBACK_GAS = 200000; uint32 constant AUTO_MODE_SCHEDULED_CALLBACK_GAS = 3800431; } interface IUniswapRouter { // Get Factory and WETH addresses. function factory() external pure returns (address); function WETH() external pure returns (address); // Create/add to a liquidity pair using ETH. function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns ( uint amountToken, uint amountETH, uint liquidity ); // Remove liquidity pair. function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns ( uint amountETH ); // Get trade output amount, given an input. function getAmountsOut( uint amountIn, address[] memory path ) external view returns ( uint[] memory amounts ); // Get trade input amount, given an output. function getAmountsIn( uint amountOut, address[] memory path ) external view returns ( uint[] memory amounts ); } interface IUniswapFactory { function getPair( address tokenA, address tokenB ) external view returns ( address pair ); } contract UniLotteryConfigGenerator { function getConfig() external pure returns( Lottery.LotteryConfig memory cfg ) { cfg.initialFunds = 10 ether; } } contract UniLotteryLotteryFactory { // Uniswap Router address on this network - passed to Lotteries on // construction. //ddress payable immutable uniRouterAddress; // Delegate Contract for the Lottery, containing all logic code // needed for deploying LotteryStubs. // Deployed only once, on construction. address payable immutable public delegateContract; // The Pool Address. address payable poolAddress; // The Lottery Storage Factory address, that the Lottery contracts use. UniLotteryStorageFactory lotteryStorageFactory; // Pool-Only modifier. modifier poolOnly { require( msg.sender == poolAddress/*, "Function can only be called by the Main Pool!" */); _; } // Constructor. // Set the Uniswap Address, and deploy&lock the Delegate Code contract. // constructor( /*address payable _uniRouter*/ ) { //uniRouterAddress = _uniRouter; delegateContract = address( uint160( address( new Lottery() ) ) ); } // Initialization function. // Set the poolAddress as msg.sender, and lock it. // Also, set the Lottery Storage Factory contract instance address. function initialize( address _storageFactoryAddress ) external { require( poolAddress == address( 0 )/*, "Initialization has already finished!" */); // Set the Pool's Address. // Lock it. No more calls to this function will be executed. poolAddress = msg.sender; // Set the Storage Factory, and initialize it! lotteryStorageFactory = UniLotteryStorageFactory( _storageFactoryAddress ); lotteryStorageFactory.initialize(); } /** * Deploy a new Lottery Stub from the specified config. * @param config - Lottery Config to be used (passed by the pool). * @return newLottery - the newly deployed lottery stub. */ function createNewLottery( Lottery.LotteryConfig memory config, address randomnessProvider ) public poolOnly returns( address payable newLottery ) { // Create new Lottery Storage, using storage factory. // Populate the stub, by calling the "construct" function. LotteryStub stub = new LotteryStub(); stub.stub_construct( delegateContract ); Lottery( address( stub ) ).construct( config, poolAddress, randomnessProvider, lotteryStorageFactory.createNewStorage() ); return address( stub ); } } contract LotteryStub { // ============ ERC20 token contract's storage ============ // // ------- Slot ------- // // Balances of token holders. mapping (address => uint256) private _balances; // ------- Slot ------- // // Allowances of spenders for a specific token owner. mapping (address => mapping (address => uint256)) private _allowances; // ------- Slot ------- // // Total supply of the token. uint256 private _totalSupply; // ============== Lottery contract's storage ============== // // ------- Initial Slots ------- // // The config which is passed to constructor. Lottery.LotteryConfig internal cfg; // ------- Slot ------- // // The Lottery Storage contract, which stores all holder data, // such as scores, referral tree data, etc. LotteryStorage /*public*/ lotStorage; // ------- Slot ------- // // Pool address. Set on constructor from msg.sender. address payable /*public*/ poolAddress; // ------- Slot ------- // // Randomness Provider address. address /*public*/ randomnessProvider; // ------- Slot ------- // // Exchange address. In Uniswap mode, it's the Uniswap liquidity // pair's address, where trades execute. address /*public*/ exchangeAddress; // Start date. uint32 /*public*/ startDate; // Completion (Mining Phase End) date. uint32 /*public*/ completionDate; // The date when Randomness Provider was called, requesting a // random seed for the lottery finish. // Also, when this variable becomes Non-Zero, it indicates that we're // on Ending Stage Part One: waiting for the random seed. uint32 finish_timeRandomSeedRequested; // ------- Slot ------- // // WETH address. Set by calling Router's getter, on constructor. address WETHaddress; // Is the WETH first or second token in our Uniswap Pair? bool uniswap_ethFirst; // If we are, or were before, on finishing stage, this is the // probability of lottery going to Ending Stage on this transaction. uint32 finishProbablity; // Re-Entrancy Lock (Mutex). // We protect for reentrancy in the Fund Transfer functions. bool reEntrancyMutexLocked; // On which stage we are currently. uint8 /*public*/ lotteryStage; // Indicator for whether the lottery fund gains have passed a // minimum fund gain requirement. // After that time point (when this bool is set), the token sells // which could drop the fund value below the requirement, would // be denied. bool fundGainRequirementReached; // The current step of the Mining Stage. uint16 miningStep; // If we're currently on Special Transfer Mode - that is, we allow // direct transfers between parties even in NON-ACTIVE state. bool specialTransferModeEnabled; // ------- Slot ------- // // Per-Transaction Pseudo-Random hash value (transferHashValue). // This value is computed on every token transfer, by keccak'ing // the last (current) transferHashValue, msg.sender, block.timestamp, and // transaction count. // // This is used on Finishing Stage, as a pseudo-random number, // which is used to check if we should end the lottery (move to // Ending Stage). uint256 transferHashValue; // ------- Slot ------- // // On lottery end, get & store the lottery total ETH return // (including initial funds), and profit amount. uint128 /*public*/ ending_totalReturn; uint128 /*public*/ ending_profitAmount; // ------- Slot ------- // // The mapping that contains TRUE for addresses that already claimed // their lottery winner prizes. // Used only in COMPLETION, on claimWinnerPrize(), to check if // msg.sender has already claimed his prize. mapping( address => bool ) /*public*/ prizeClaimersAddresses; // =================== OUR CONTRACT'S OWN STORAGE =================== // // The address of the delegate contract, containing actual logic. address payable public __delegateContract; // =================== Functions =================== // // Constructor. // Just set the delegate's address. function stub_construct( address payable _delegateAddr ) external { require( __delegateContract == address(0) ); __delegateContract = _delegateAddr; } // Fallback payable function, which delegates any call to our // contract, into the delegate contract. fallback() external payable { // DelegateCall the delegate code contract. ( bool success, bytes memory data ) = __delegateContract.delegatecall( msg.data ); // Use inline assembly to be able to return value from the fallback. // (by default, returning a value from fallback is not possible, // but it's still possible to manually copy data to the // return buffer. assembly { // delegatecall returns 0 (false) on error. // Add 32 bytes to "data" pointer, because first slot (32 bytes) // contains the length, and we use return value's length // from returndatasize() opcode. switch success case 0 { revert( add( data, 32 ), returndatasize() ) } default { return( add( data, 32 ), returndatasize() ) } } } // Receive ether function. receive() external payable { } } contract LotteryStorageStub { // =============== LotteryStorage contract's storage ================ // // --------- Slot --------- // // The Lottery address that this storage belongs to. // Is set by the "initialize()", called by corresponding Lottery. address lottery; // The Random Seed, that was passed to us from Randomness Provider, // or generated alternatively. uint64 randomSeed; // The actual number of winners that there will be. Set after // completing the Winner Selection Algorithm. uint16 numberOfWinners; // Bool indicating if Winner Selection Algorithm has been executed. bool algorithmCompleted; // --------- Slot --------- // // Winner Algorithm config. Specified in Initialization(). LotteryStorage.WinnerAlgorithmConfig algConfig; // --------- Slot --------- // // The Min-Max holder score storage. LotteryStorage.MinMaxHolderScores minMaxScores; // --------- Slot --------- // // Array of holders. address[] /*public*/ holders; // --------- Slot --------- // // Holder array indexes mapping, for O(1) array element access. mapping( address => uint ) holderIndexes; // --------- Slot --------- // // Mapping of holder data. mapping( address => LotteryStorage.HolderData ) /*public*/ holderData; // --------- Slot --------- // // Mapping of referral IDs to addresses of holders who generated // those IDs. mapping( uint256 => address ) referrers; // --------- Slot --------- // // The array of final-sorted winners (set after Winner Selection // Algorithm completes), that contains the winners' indexes // in the "holders" array, to save space. // // Notice that by using uint16, we can fit 16 items into one slot! // So, if there are 160 winners, we only take up 10 slots, so // only 20,000 * 10 = 200,000 gas gets consumed! // LotteryStorage.WinnerIndexStruct[] sortedWinnerIndexes; // =================== OUR CONTRACT'S OWN STORAGE =================== // // The address of the delegate contract, containing actual logic. address public __delegateContract; // =================== Functions =================== // // Constructor. // Just set the delegate's address. function stub_construct( address _delegateAddr ) external { require( __delegateContract == address(0) ); __delegateContract = _delegateAddr; } // Fallback function, which delegates any call to our // contract, into the delegate contract. fallback() external { // DelegateCall the delegate code contract. ( bool success, bytes memory data ) = __delegateContract.delegatecall( msg.data ); // Use inline assembly to be able to return value from the fallback. // (by default, returning a value from fallback is not possible, // but it's still possible to manually copy data to the // return buffer. assembly { // delegatecall returns 0 (false) on error. // Add 32 bytes to "data" pointer, because first slot (32 bytes) // contains the length, and we use return value's length // from returndatasize() opcode. switch success case 0 { revert( add( data, 32 ), returndatasize() ) } default { return( add( data, 32 ), returndatasize() ) } } } } interface IUniLotteryPool { function lotteryFinish( uint totalReturn, uint profitAmount ) external payable; } interface IRandomnessProvider { function requestRandomSeedForLotteryFinish() external; } contract LotteryStorage is CoreUniLotterySettings { // ==================== Structs & Constants ==================== // // Struct of holder data & scores. struct HolderData { // --------- Slot --------- // // If this holder provided a valid referral ID, this is the // address of a referrer - the user who generated the said // referral ID. address referrer; // Bonus score points, which can be given in certain events, // such as when player registers a valid referral ID. int16 bonusScore; // Number of all child referrees, including multi-level ones. // Updated by traversing child->parent way, incrementing // every node's counter by one. // Used in Winner Selection Algorithm, to determine how much // to divide the accumulated referree scores by. uint16 referreeCount; // --------- Slot --------- // // If this holder has generated his own referral ID, this is // that ID. If he hasn't generated an ID, this is zero. uint256 referralID; // --------- Slot --------- // // The intermediate individual score factor variables. // Ether contributed: ( buys - sells ). Can be negative. int40 etherContributed; // Time x ether factor: (relativeTxTime * etherAmount). int40 timeFactors; // Token balance score factor of this holder - we use int, // for easier computation of player scores in our algorithms. int40 tokenBalance; // Accumulated referree score factors - ether contributed by // all referrees, time factors, and token balances of all // referrees. int40 referree_etherContributed; int40 referree_timeFactors; int40 referree_tokenBalance; } // Final Score (end lottery score * randomValue) structure. struct FinalScore { address addr; // 20 bytes \ uint16 holderIndex; // 2 bytes | = 30 bytes => 1 slot. uint64 score; // 8 bytes / } // Winner Indexes structure - used to efficiently store Winner // indexes in holder's array, after completing the Winner Selection // Algorithm. // To save Space, we store these in a struct, with uint16 array // with 16 items - so this struct takes up excactly 1 slot. struct WinnerIndexStruct { uint16[ 16 ] indexes; } // A structure which is used by Winner Selection algorithm, // which is a subset of the LotteryConfig structure, containing // only items necessary for executing the Winner Selection algorigm. // More detailed member description can be found in LotteryConfig // structure description. // Takes up only one slot! struct WinnerAlgorithmConfig { // --------- Slot --------- // // Individual player max score parts. int16 maxPlayerScore_etherContributed; int16 maxPlayerScore_tokenHoldingAmount; int16 maxPlayerScore_timeFactor; int16 maxPlayerScore_refferalBonus; // Number of lottery winners. uint16 winnerCount; // Score-To-Random ration data (as a rational ratio number). // For example if 1:5, then scorePart = 1, and randPart = 5. uint16 randRatio_scorePart; uint16 randRatio_randPart; // The Ending Algorithm type. uint8 endingAlgoType; } // Structure containing the minimum and maximum values of // holder intermediate scores. // These values get updated on transfers during ACTIVE stage, // when holders buy/sell tokens. // // Used in winner selection algorithm, to normalize the scores in // a single loop, to avoid looping additional time to find min/max. // // Structure takes up only a single slot! // struct MinMaxHolderScores { // --------- Slot --------- // int40 holderScore_etherContributed_min; int40 holderScore_etherContributed_max; int40 holderScore_timeFactors_min; int40 holderScore_timeFactors_max; int40 holderScore_tokenBalance_min; int40 holderScore_tokenBalance_max; } // Referral score variant of the structure above. // Also, only a single slot! // struct MinMaxReferralScores { // --------- Slot --------- // // Min&Max values for referrer scores. int40 referralScore_etherContributed_min; int40 referralScore_etherContributed_max; int40 referralScore_timeFactors_min; int40 referralScore_timeFactors_max; int40 referralScore_tokenBalance_min; int40 referralScore_tokenBalance_max; } // ROOT_REFERRER constant. // Used to prevent cyclic dependencies on referral tree. address constant ROOT_REFERRER = address( 1 ); // Max referral tree depth - maximum number of referrees that // a referrer can get. uint constant MAX_REFERRAL_DEPTH = 10; // Precision of division operations. int constant PRECISION = 10000; // Random number modulo to use when obtaining random numbers from // the random seed + nonce, using keccak256. // This is the maximum available Score Random Factor, plus one. // By default, 10^9 (one billion). // uint constant RANDOM_MODULO = (10 ** 9); // Maximum number of holders that the MinedWinnerSelection algorithm // can process. Related to block gas limit. uint constant MINEDSELECTION_MAX_NUMBER_OF_HOLDERS = 300; // Maximum number of holders that the WinnerSelfValidation algorithm // can process. Related to block gas limit. uint constant SELFVALIDATION_MAX_NUMBER_OF_HOLDERS = 1200; // ==================== State Variables ==================== // // --------- Slot --------- // // The Lottery address that this storage belongs to. // Is set by the "initialize()", called by corresponding Lottery. address lottery; // The Random Seed, that was passed to us from Randomness Provider, // or generated alternatively. uint64 randomSeed; // The actual number of winners that there will be. Set after // completing the Winner Selection Algorithm. uint16 numberOfWinners; // Bool indicating if Winner Selection Algorithm has been executed. bool algorithmCompleted; // --------- Slot --------- // // Winner Algorithm config. Specified in Initialization(). WinnerAlgorithmConfig algConfig; // --------- Slot --------- // // The Min-Max holder score storage. MinMaxHolderScores public minMaxScores; MinMaxReferralScores public minMaxReferralScores; // --------- Slot --------- // // Array of holders. address[] public holders; // --------- Slot --------- // // Holder array indexes mapping, for O(1) array element access. mapping( address => uint ) holderIndexes; // --------- Slot --------- // // Mapping of holder data. mapping( address => HolderData ) public holderData; // --------- Slot --------- // // Mapping of referral IDs to addresses of holders who generated // those IDs. mapping( uint256 => address ) referrers; // --------- Slot --------- // // The array of final-sorted winners (set after Winner Selection // Algorithm completes), that contains the winners' indexes // in the "holders" array, to save space. // // Notice that by using uint16, we can fit 16 items into one slot! // So, if there are 160 winners, we only take up 10 slots, so // only 20,000 * 10 = 200,000 gas gets consumed! // WinnerIndexStruct[] sortedWinnerIndexes; // ============== Internal (Private) Functions ============== // // Lottery-Only modifier. modifier lotteryOnly { require( msg.sender == address( lottery )/*, "Function can only be called by Lottery that this" "Storage Contract belongs to!" */); _; } // ============== [ BEGIN ] LOTTERY QUICKSORT FUNCTIONS ============== // /** * QuickSort and QuickSelect algorithm functionality code. * * These algorithms are used to find the lottery winners in * an array of final random-factored scores. * As the highest-scorers win, we need to sort an array to * identify them. * * For this task, we use QuickSelect to partition array into * winner part (elements with score larger than X, where X is * n-th largest element, where n is number of winners), * and others (non-winners), who are ignored to save computation * power. * Then we sort the winner part only, using QuickSort, and * distribute prizes to winners accordingly. */ // Swap function used in QuickSort algorithms. // function QSort_swap( FinalScore[] memory list, uint a, uint b ) internal pure { FinalScore memory tmp = list[ a ]; list[ a ] = list[ b ]; list[ b ] = tmp; } // Standard Hoare's partition scheme function, used for both // QuickSort and QuickSelect. // function QSort_partition( FinalScore[] memory list, int lo, int hi ) internal pure returns( int newPivotIndex ) { uint64 pivot = list[ uint( hi + lo ) / 2 ].score; int i = lo - 1; int j = hi + 1; while( true ) { do { i++; } while( list[ uint( i ) ].score > pivot ) ; do { j--; } while( list[ uint( j ) ].score < pivot ) ; if( i >= j ) return j; QSort_swap( list, uint( i ), uint( j ) ); } } // QuickSelect's Lomuto partition scheme. // function QSort_LomutoPartition( FinalScore[] memory list, uint left, uint right, uint pivotIndex ) internal pure returns( uint newPivotIndex ) { uint pivotValue = list[ pivotIndex ].score; QSort_swap( list, pivotIndex, right ); // Move pivot to end uint storeIndex = left; for( uint i = left; i < right; i++ ) { if( list[ i ].score > pivotValue ) { QSort_swap( list, storeIndex, i ); storeIndex++; } } // Move pivot to its final place, and return the pivot's index. QSort_swap( list, right, storeIndex ); return storeIndex; } // QuickSelect algorithm (iterative). // function QSort_QuickSelect( FinalScore[] memory list, int left, int right, int k ) internal pure returns( int indexOfK ) { while( true ) { if( left == right ) return left; int pivotIndex = int( QSort_LomutoPartition( list, uint(left), uint(right), uint(right) ) ); if( k == pivotIndex ) return k; else if( k < pivotIndex ) right = pivotIndex - 1; else left = pivotIndex + 1; } } // Standard QuickSort function. // function QSort_QuickSort( FinalScore[] memory list, int lo, int hi ) internal pure { if( lo < hi ) { int p = QSort_partition( list, lo, hi ); QSort_QuickSort( list, lo, p ); QSort_QuickSort( list, p + 1, hi ); } } // ============== [ END ] LOTTERY QUICKSORT FUNCTIONS ============== // // ------------ Ending Stage - Winner Selection Algorithm ------------ // /** * Compute the individual player score factors for a holder. * Function split from the below one (ending_Stage_2), to avoid * "Stack too Deep" errors. */ function computeHolderIndividualScores( WinnerAlgorithmConfig memory cfg, MinMaxHolderScores memory minMax, HolderData memory hdata ) internal pure returns( int individualScore ) { // Normalize the scores, by subtracting minimum and dividing // by maximum, to get the score values specified in cfg. // Use precision of 100, then round. // // Notice that we're using int arithmetics, so division // truncates. That's why we use PRECISION, to simulate // rounding. // // This formula is better explained in example. // In this example, we use variable abbreviations defined // below, on formula's right side comments. // // Say, values are these in our example: // e = 4, eMin = 1, eMax = 8, MS = 5, P = 10. // // So, let's calculate the score using the formula: // ( ( ( (4 - 1) * 10 * 5 ) / (8 - 1) ) + (10 / 2) ) / 10 = // ( ( ( 3 * 10 * 5 ) / 7 ) + 5 ) / 10 = // ( ( 150 / 7 ) + 5 ) / 10 = // ( ( 150 / 7 ) + 5 ) / 10 = // ( 20 + 5 ) / 10 = // 25 / 10 = // [ 2.5 ] = 2 // // So, with truncation, we see that for e = 4, the score // is 2 out of 5 maximum. // That's because the minimum ether contributed was 1, and // maximum was 8. // So, 4 stays below the middle, and gets a nicely rounded // score of 2. // Compute etherContributed. int score_etherContributed = ( ( ( int( hdata.etherContributed - // e minMax.holderScore_etherContributed_min ) // eMin * PRECISION * cfg.maxPlayerScore_etherContributed )// P * MS / int( minMax.holderScore_etherContributed_max - // eMax minMax.holderScore_etherContributed_min ) // eMin ) + (PRECISION / 2) ) / PRECISION; // Compute timeFactors. int score_timeFactors = ( ( ( int( hdata.timeFactors - // e minMax.holderScore_timeFactors_min ) // eMin * PRECISION * cfg.maxPlayerScore_timeFactor ) // P * MS / int( minMax.holderScore_timeFactors_max - // eMax minMax.holderScore_timeFactors_min ) // eMin ) + (PRECISION / 2) ) / PRECISION; // Compute tokenBalance. int score_tokenBalance = ( ( ( int( hdata.tokenBalance - // e minMax.holderScore_tokenBalance_min ) // eMin * PRECISION * cfg.maxPlayerScore_tokenHoldingAmount ) / int( minMax.holderScore_tokenBalance_max - // eMax minMax.holderScore_tokenBalance_min ) // eMin ) + (PRECISION / 2) ) / PRECISION; // Return the accumulated individual score (excluding referrees). return score_etherContributed + score_timeFactors + score_tokenBalance; } /** * Compute the unified Referree-Score of a player, who's got * the accumulated factor-scores of all his referrees in his * holderData structure. * * @param individualToReferralRatio - an int value, computed * before starting the winner score computation loop, in * the ending_Stage_2 initial part, to save computation * time later. * This is the ratio of the maximum available referral score, * to the maximum available individual score, as defined in * the config (for example, if max.ref.score is 20, and * max.ind.score is 40, then the ratio is 20/40 = 0.5). * * We use this ratio to transform the computed accumulated * referree individual scores to the standard referrer's * score, by multiplying by that ratio. */ function computeReferreeScoresForHolder( int individualToReferralRatio, WinnerAlgorithmConfig memory cfg, MinMaxReferralScores memory minMax, HolderData memory hdata ) internal pure returns( int unifiedReferreeScore ) { // If number of referrees of this HODLer is Zero, then // his referree score is also zero. if( hdata.referreeCount == 0 ) return 0; // Now, compute the Referree's Accumulated Scores. // // Here we use the same formula as when computing individual // scores (in the function above), but we use referree parts // instead. // Compute etherContributed. int referreeScore_etherContributed = ( ( ( int( hdata.referree_etherContributed - minMax.referralScore_etherContributed_min ) * PRECISION * cfg.maxPlayerScore_etherContributed ) / int( minMax.referralScore_etherContributed_max - minMax.referralScore_etherContributed_min ) ) ); // Compute timeFactors. int referreeScore_timeFactors = ( ( ( int( hdata.referree_timeFactors - minMax.referralScore_timeFactors_min ) * PRECISION * cfg.maxPlayerScore_timeFactor ) / int( minMax.referralScore_timeFactors_max - minMax.referralScore_timeFactors_min ) ) ); // Compute tokenBalance. int referreeScore_tokenBalance = ( ( ( int( hdata.referree_tokenBalance - minMax.referralScore_tokenBalance_min ) * PRECISION * cfg.maxPlayerScore_tokenHoldingAmount ) / int( minMax.referralScore_tokenBalance_max - minMax.referralScore_tokenBalance_min ) ) ); // Accumulate 'em all ! // Then, multiply it by the ratio of all individual max scores // (maxPlayerScore_etherContributed, timeFactor, tokenBalance), // to the maxPlayerScore_refferalBonus. // Use the same precision. unifiedReferreeScore = int( ( ( ( ( referreeScore_etherContributed + referreeScore_timeFactors + referreeScore_tokenBalance ) + (PRECISION / 2) ) / PRECISION ) * individualToReferralRatio ) / PRECISION ); } /** * Update Min & Max values for individual holder scores. */ function priv_updateMinMaxScores_individual( MinMaxHolderScores memory minMax, int40 _etherContributed, int40 _timeFactors, int40 _tokenBalance ) internal pure { // etherContributed: if( _etherContributed > minMax.holderScore_etherContributed_max ) minMax.holderScore_etherContributed_max = _etherContributed; if( _etherContributed < minMax.holderScore_etherContributed_min ) minMax.holderScore_etherContributed_min = _etherContributed; // timeFactors: if( _timeFactors > minMax.holderScore_timeFactors_max ) minMax.holderScore_timeFactors_max = _timeFactors; if( _timeFactors < minMax.holderScore_timeFactors_min ) minMax.holderScore_timeFactors_min = _timeFactors; // tokenBalance: if( _tokenBalance > minMax.holderScore_tokenBalance_max ) minMax.holderScore_tokenBalance_max = _tokenBalance; if( _tokenBalance < minMax.holderScore_tokenBalance_min ) minMax.holderScore_tokenBalance_min = _tokenBalance; } /** * Update Min & Max values for referral scores. */ function priv_updateMinMaxScores_referral( MinMaxReferralScores memory minMax, int40 _etherContributed, int40 _timeFactors, int40 _tokenBalance ) internal pure { // etherContributed: if( _etherContributed > minMax.referralScore_etherContributed_max ) minMax.referralScore_etherContributed_max = _etherContributed; if( _etherContributed < minMax.referralScore_etherContributed_min ) minMax.referralScore_etherContributed_min = _etherContributed; // timeFactors: if( _timeFactors > minMax.referralScore_timeFactors_max ) minMax.referralScore_timeFactors_max = _timeFactors; if( _timeFactors < minMax.referralScore_timeFactors_min ) minMax.referralScore_timeFactors_min = _timeFactors; // tokenBalance: if( _tokenBalance > minMax.referralScore_tokenBalance_max ) minMax.referralScore_tokenBalance_max = _tokenBalance; if( _tokenBalance < minMax.referralScore_tokenBalance_min ) minMax.referralScore_tokenBalance_min = _tokenBalance; } // =================== PUBLIC FUNCTIONS =================== // /** * Update current holder's score with given change values, and * Propagate the holder's current transfer's score changes * through the referral chain, updating every parent referrer's * accumulated referree scores, until the ROOT_REFERRER or zero * address referrer is encountered. */ function updateAndPropagateScoreChanges( address holder, int __etherContributed_change, int __timeFactors_change, int __tokenBalance_change ) public lotteryOnly { // Convert the data into shrinked format - leave only // 4 decimals of Ether precision, and drop the decimal part // of ULT tokens absolutely. // Don't change TimeFactors, as it is already adjusted in // Lottery contract's code. int40 timeFactors_change = int40( __timeFactors_change ); int40 etherContributed_change = int40( __etherContributed_change / int(1 ether / 10000) ); int40 tokenBalance_change = int40( __tokenBalance_change / int(1 ether) ); // Update current holder's score. holderData[ holder ].etherContributed += etherContributed_change; holderData[ holder ].timeFactors += timeFactors_change; holderData[ holder ].tokenBalance += tokenBalance_change; // Check if scores are exceeding current min/max scores, // and if so, update the min/max scores. MinMaxHolderScores memory minMaxCpy = minMaxScores; MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores; priv_updateMinMaxScores_individual( minMaxCpy, holderData[ holder ].etherContributed, holderData[ holder ].timeFactors, holderData[ holder ].tokenBalance ); // Propagate the score through the referral chain. // Dive at maximum to the depth of 10, to avoid "Outta Gas" // errors. uint depth = 0; address referrerAddr = holderData[ holder ].referrer; while( referrerAddr != ROOT_REFERRER && referrerAddr != address( 0 ) && depth < MAX_REFERRAL_DEPTH ) { // Update this referrer's accumulated referree scores. holderData[ referrerAddr ].referree_etherContributed += etherContributed_change; holderData[ referrerAddr ].referree_timeFactors += timeFactors_change; holderData[ referrerAddr ].referree_tokenBalance += tokenBalance_change; // Update MinMax according to this referrer's score. priv_updateMinMaxScores_referral( minMaxRefCpy, holderData[ referrerAddr ].referree_etherContributed, holderData[ referrerAddr ].referree_timeFactors, holderData[ referrerAddr ].referree_tokenBalance ); // Move to the higher-level referrer. referrerAddr = holderData[ referrerAddr ].referrer; depth++; } // Check if MinMax have changed. If so, update it. if( keccak256( abi.encode( minMaxCpy ) ) != keccak256( abi.encode( minMaxScores ) ) ) minMaxScores = minMaxCpy; // Check referral part. if( keccak256( abi.encode( minMaxRefCpy ) ) != keccak256( abi.encode( minMaxReferralScores ) ) ) minMaxReferralScores = minMaxRefCpy; } /** * Pure function to fix an in-memory copy of MinMaxScores, * by changing equal min-max pairs to differ by one. * This is needed to avoid division-by-zero in some calculations. */ function priv_fixMinMaxIfEqual( MinMaxHolderScores memory minMaxCpy, MinMaxReferralScores memory minMaxRefCpy ) internal pure { // Individual part if( minMaxCpy.holderScore_etherContributed_min == minMaxCpy.holderScore_etherContributed_max ) minMaxCpy.holderScore_etherContributed_max = minMaxCpy.holderScore_etherContributed_min + 1; if( minMaxCpy.holderScore_timeFactors_min == minMaxCpy.holderScore_timeFactors_max ) minMaxCpy.holderScore_timeFactors_max = minMaxCpy.holderScore_timeFactors_min + 1; if( minMaxCpy.holderScore_tokenBalance_min == minMaxCpy.holderScore_tokenBalance_max ) minMaxCpy.holderScore_tokenBalance_max = minMaxCpy.holderScore_tokenBalance_min + 1; // Referral part if( minMaxRefCpy.referralScore_etherContributed_min == minMaxRefCpy.referralScore_etherContributed_max ) minMaxRefCpy.referralScore_etherContributed_max = minMaxRefCpy.referralScore_etherContributed_min + 1; if( minMaxRefCpy.referralScore_timeFactors_min == minMaxRefCpy.referralScore_timeFactors_max ) minMaxRefCpy.referralScore_timeFactors_max = minMaxRefCpy.referralScore_timeFactors_min + 1; if( minMaxRefCpy.referralScore_tokenBalance_min == minMaxRefCpy.referralScore_tokenBalance_max ) minMaxRefCpy.referralScore_tokenBalance_max = minMaxRefCpy.referralScore_tokenBalance_min + 1; } /** * Function executes the Lottery Winner Selection Algorithm, * and writes the final, sorted array, containing winner rankings. * * This function is called from the Lottery's Mining Stage Step 2, * * This is the final function that lottery performs actively - * and arguably the most important - because it determines * lottery winners through Winner Selection Algorithm. * * The random seed must be already set, before calling this function. */ function executeWinnerSelectionAlgorithm() public lotteryOnly { // Copy the Winner Algo Config into memory, to avoid using // 400-gas costing SLOAD every time we need to load something. WinnerAlgorithmConfig memory cfg = algConfig; // Can only be performed if algorithm is MinedWinnerSelection! require( cfg.endingAlgoType == uint8(Lottery.EndingAlgoType.MinedWinnerSelection)/*, "Algorithm cannot be performed on current Algo-Type!" */); // Now, we gotta find the winners using a Randomized Score-Based // Winner Selection Algorithm. // // During transfers, all player intermediate scores // (etherContributed, timeFactors, and tokenBalances) were // already set in every holder's HolderData structure, // during operations of updateHolderData_preTransfer() function. // // Minimum and maximum values are also known, so normalization // will be easy. // All referral tree score data were also properly propagated // during operations of updateAndPropagateScoreChanges() function. // // All we block.timestamp have to do, is loop through holder array, and // compute randomized final scores for every holder, into // the Final Score array. // Declare the Final Score array - computed for all holders. uint ARRLEN = ( holders.length > MINEDSELECTION_MAX_NUMBER_OF_HOLDERS ? MINEDSELECTION_MAX_NUMBER_OF_HOLDERS : holders.length ); FinalScore[] memory finalScores = new FinalScore[] ( ARRLEN ); // Compute the precision-adjusted constant ratio of // referralBonus max score to the player individual max scores. int individualToReferralRatio = ( PRECISION * cfg.maxPlayerScore_refferalBonus ) / ( int( cfg.maxPlayerScore_etherContributed ) + int( cfg.maxPlayerScore_timeFactor ) + int( cfg.maxPlayerScore_tokenHoldingAmount ) ); // Max available player score. int maxAvailablePlayerScore = int( cfg.maxPlayerScore_etherContributed + cfg.maxPlayerScore_timeFactor + cfg.maxPlayerScore_tokenHoldingAmount + cfg.maxPlayerScore_refferalBonus ); // Random Factor of scores, to maintain random-to-determined // ratio equal to specific value (1:5 for example - // "randPart" == 5/*, "scorePart" */== 1). // // maxAvailablePlayerScore * FACT --- scorePart // RANDOM_MODULO --- randPart // // RANDOM_MODULO * scorePart // maxAvailablePlayerScore * FACT = ------------------------- // randPart // // RANDOM_MODULO * scorePart // FACT = -------------------------------------- // randPart * maxAvailablePlayerScore int SCORE_RAND_FACT = ( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) / ( int(cfg.randRatio_randPart) * maxAvailablePlayerScore ); // Fix Min-Max scores, to avoid division by zero, if min == max. // If min == max, make the difference equal to 1. MinMaxHolderScores memory minMaxCpy = minMaxScores; MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores; priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy ); // Loop through all the holders. for( uint i = 0; i < ARRLEN; i++ ) { // Fetch the needed holder data to in-memory hdata variable, // to save gas on score part computing functions. HolderData memory hdata; // Slot 1: hdata.etherContributed = holderData[ holders[ i ] ].etherContributed; hdata.timeFactors = holderData[ holders[ i ] ].timeFactors; hdata.tokenBalance = holderData[ holders[ i ] ].tokenBalance; hdata.referreeCount = holderData[ holders[ i ] ].referreeCount; // Slot 2: hdata.referree_etherContributed = holderData[ holders[ i ] ].referree_etherContributed; hdata.referree_timeFactors = holderData[ holders[ i ] ].referree_timeFactors; hdata.referree_tokenBalance = holderData[ holders[ i ] ].referree_tokenBalance; hdata.bonusScore = holderData[ holders[ i ] ].bonusScore; // Now, add bonus score, and compute total player's score: // Bonus part, individual score part, and referree score part. int totalPlayerScore = hdata.bonusScore + computeHolderIndividualScores( cfg, minMaxCpy, hdata ) + computeReferreeScoresForHolder( individualToReferralRatio, cfg, minMaxRefCpy, hdata ); // Check if total player score <= 0. If so, make it equal // to 1, because otherwise randomization won't be possible. if( totalPlayerScore <= 0 ) totalPlayerScore = 1; // Now, check if it's not more than max! If so, lowerify. // This could have happen'd because of bonus. if( totalPlayerScore > maxAvailablePlayerScore ) totalPlayerScore = maxAvailablePlayerScore; // Multiply the score by the Random Modulo Adjustment // Factor, to get fairer ratio of random-to-determined data. totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) / ( PRECISION ); // Score is computed! // Now, randomize it, and add to Final Scores Array. // We use keccak to generate a random number from random seed, // using holder's address as a nonce. uint modulizedRandomNumber = uint( keccak256( abi.encodePacked( randomSeed, holders[ i ] ) ) ) % RANDOM_MODULO; // Add the random number, to introduce the random factor. // Ratio of (current) totalPlayerScore to modulizedRandomNumber // is the same as ratio of randRatio_scorePart to // randRatio_randPart. uint endScore = uint( totalPlayerScore ) + modulizedRandomNumber; // Finally, set this holder's final score data. finalScores[ i ].addr = holders[ i ]; finalScores[ i ].holderIndex = uint16( i ); finalScores[ i ].score = uint64( endScore ); } // All final scores are block.timestamp computed. // Sort the array, to find out the highest scores! // Firstly, partition an array to only work on top K scores, // where K is the number of winners. // There can be a rare case where specified number of winners is // more than lottery token holders. We got that covered. require( finalScores.length > 0 ); uint K = cfg.winnerCount - 1; if( K > finalScores.length-1 ) K = finalScores.length-1; // Must be THE LAST ELEMENT's INDEX. // Use QuickSelect to do this. QSort_QuickSelect( finalScores, 0, int( finalScores.length - 1 ), int( K ) ); // Now, QuickSort only the first K items, because the rest // item scores are not high enough to become winners. QSort_QuickSort( finalScores, 0, int( K ) ); // Now, the winner array is sorted, with the highest scores // sitting at the first positions! // Let's set up the winner indexes array, where we'll store // the winners' indexes in the holders array. // So, if this array is [8, 2, 3], that means that // Winner #1 is holders[8], winner #2 is holders[2], and // winner #3 is holders[3]. // Set the Number Of Winners variable. numberOfWinners = uint16( K + 1 ); // Now, we can loop through the first numberOfWinners elements, to set // the holder indexes! // Loop through 16 elements at a time, to fill the structs. for( uint offset = 0; offset < numberOfWinners; offset += 16 ) { WinnerIndexStruct memory windStruct; uint loopStop = ( offset + 16 > numberOfWinners ? numberOfWinners : offset + 16 ); for( uint i = offset; i < loopStop; i++ ) { windStruct.indexes[ i - offset ] =finalScores[ i ].holderIndex; } // Push this block.timestamp-filled struct to the storage array! sortedWinnerIndexes.push( windStruct ); } // That's it! We're done! algorithmCompleted = true; } /** * Add a holder to holders array. * @param holder - address of a holder to add. */ function addHolder( address holder ) public lotteryOnly { // Add it to list, and set index in the mapping. holders.push( holder ); holderIndexes[ holder ] = holders.length - 1; } /** * Removes the holder 'sender' from the Holders Array. * However, this holder's HolderData structure persists! * * Notice that no index validity checks are performed, so, if * 'sender' is not present in "holderIndexes" mapping, this * function will remove the 0th holder instead! * This is not a problem for us, because Lottery calls this * function only when it's absolutely certain that 'sender' is * present in the holders array. * * @param sender - address of a holder to remove. * Named 'sender', because when token sender sends away all * his tokens, he must then be removed from holders array. */ function removeHolder( address sender ) public lotteryOnly { // Get index of the sender address in the holders array. uint index = holderIndexes[ sender ]; // Remove the sender from array, by copying last element's // value into the index'th element, where sender was before. holders[ index ] = holders[ holders.length - 1 ]; // Remove the last element of array, which we've just copied. holders.pop(); // Update indexes: remove the sender's index from the mapping, // and change the previoulsy-last element's index to the // one where we copied it - where sender was before. delete holderIndexes[ sender ]; holderIndexes[ holders[ index ] ] = index; } /** * Get holder array length. */ function getHolderCount() public view returns( uint ) { return holders.length; } /** * Generate a referral ID for a token holder. * Referral ID is used to refer other wallets into playing our * lottery. * - Referrer gets bonus points for every wallet that bought * lottery tokens and specified his referral ID. * - Referrees (wallets who got referred by registering a valid * referral ID, corresponding to some referrer), get some * bonus points for specifying (registering) a referral ID. * * Referral ID is a uint256 number, which is generated by * keccak256'ing the holder's address, holder's current * token ballance, and current time. */ function generateReferralID( address holder ) public lotteryOnly returns( uint256 referralID ) { // Check if holder has some tokens, and doesn't // have his own referral ID yet. require( holderData[ holder ].tokenBalance != 0/*, "holder doesn't have any lottery tokens!" */); require( holderData[ holder ].referralID == 0/*, "Holder already has a referral ID!" */); // Generate a referral ID with keccak. uint256 refID = uint256( keccak256( abi.encodePacked( holder, holderData[ holder ].tokenBalance, block.timestamp ) ) ); // Specify the ID as current ID of this holder. holderData[ holder ].referralID = refID; // If this holder wasn't referred by anyone (his referrer is // not set), and he's block.timestamp generated his own ID, he won't // be able to register as a referree of someone else // from block.timestamp on. // This is done to prevent circular dependency in referrals. // Do it by setting a referrer to ROOT_REFERRER address, // which is an invalid address (address(1)). if( holderData[ holder ].referrer == address( 0 ) ) holderData[ holder ].referrer = ROOT_REFERRER; // Create a new referrer with this ID. referrers[ refID ] = holder; return refID; } /** * Register a referral for a token holder, using a valid * referral ID got from a referrer. * This function is called by a referree, who obtained a * valid referral ID from some referrer, who previously * generated it using generateReferralID(). * * You can only register a referral once! * When you do so, you get bonus referral points! */ function registerReferral( address holder, int16 referralRegisteringBonus, uint256 referralID ) public lotteryOnly returns( address _referrerAddress ) { // Check if this holder has some tokens, and if he hasn't // registered a referral yet. require( holderData[ holder ].tokenBalance != 0/*, "holder doesn't have any lottery tokens!" */); require( holderData[ holder ].referrer == address( 0 )/*, "holder already has registered a referral!" */); // Create a local memory copy of minMaxReferralScores. MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores; // Get the referrer's address from his ID, and specify // it as a referrer of holder. holderData[ holder ].referrer = referrers[ referralID ]; // Bonus points are added to this holder's score for // registering a referral! holderData[ holder ].bonusScore = referralRegisteringBonus; // Increment number of referrees for every parent referrer, // by traversing a referral tree child->parent way. address referrerAddr = holderData[ holder ].referrer; // Set the return value. _referrerAddress = referrerAddr; // Traverse a tree. while( referrerAddr != ROOT_REFERRER && referrerAddr != address( 0 ) ) { // Increment referree count for this referrrer. holderData[ referrerAddr ].referreeCount++; // Update the Referrer Scores of the referrer, adding this // referree's scores to it's current values. holderData[ referrerAddr ].referree_etherContributed += holderData[ holder ].etherContributed; holderData[ referrerAddr ].referree_timeFactors += holderData[ holder ].timeFactors; holderData[ referrerAddr ].referree_tokenBalance += holderData[ holder ].tokenBalance; // Update MinMax according to this referrer's score. priv_updateMinMaxScores_referral( minMaxRefCpy, holderData[ referrerAddr ].referree_etherContributed, holderData[ referrerAddr ].referree_timeFactors, holderData[ referrerAddr ].referree_tokenBalance ); // Move to the higher-level referrer. referrerAddr = holderData[ referrerAddr ].referrer; } // Update MinMax Referral Scores if needed. if( keccak256( abi.encode( minMaxRefCpy ) ) != keccak256( abi.encode( minMaxReferralScores ) ) ) minMaxReferralScores = minMaxRefCpy; return _referrerAddress; } /** * Sets our random seed to some value. * Should be called from Lottery, after obtaining random seed from * the Randomness Provider. */ function setRandomSeed( uint _seed ) external lotteryOnly { randomSeed = uint64( _seed ); } /** * Initialization function. * Here, we bind our contract to the Lottery contract that * this Storage belongs to. * The parent lottery must call this function - hence, we set * "lottery" to msg.sender. * * When this function is called, our contract must be not yet * initialized - "lottery" address must be Zero! * * Here, we also set our Winner Algorithm config, which is a * subset of LotteryConfig, fitting into 1 storage slot. */ function initialize( WinnerAlgorithmConfig memory _wcfg ) public { require( address( lottery ) == address( 0 )/*, "Storage is already initialized!" */); // Set the Lottery address (msg.sender can't be zero), // and thus, set our contract to initialized! lottery = msg.sender; // Set the Winner-Algo-Config. algConfig = _wcfg; // NOT-NEEDED: Set initial min-max scores: min is INT_MAX. /*minMaxScores.holderScore_etherContributed_min = int80( 2 ** 78 ); minMaxScores.holderScore_timeFactors_min = int80( 2 ** 78 ); minMaxScores.holderScore_tokenBalance_min = int80( 2 ** 78 ); */ } // ==================== Views ==================== // // Returns the current random seed. // If the seed hasn't been set yet (or set to 0), returns 0. // function getRandomSeed() external view returns( uint ) { return randomSeed; } // Check if Winner Selection Algorithm has beed executed. // function minedSelection_algorithmAlreadyExecuted() external view returns( bool ) { return algorithmCompleted; } /** * After lottery has completed, this function returns if "addr" * is one of lottery winners, and the position in winner rankings. * Function is used to obtain the ranking position before * calling claimWinnerPrize() on Lottery. * * This function should be called off-chain, and then using the * retrieved data, one can call claimWinnerPrize(). */ function minedSelection_getWinnerStatus( address addr ) public view returns( bool isWinner, uint32 rankingPosition ) { // Loop through the whole winner indexes array, trying to // find if "addr" is one of the winner addresses. for( uint16 i = 0; i < numberOfWinners; i++ ) { // Check if holder on this winner ranking's index position // is addr, if so, good! uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ]; if( holders[ pos ] == addr ) { return ( true, i ); } } // The "addr" is not a winner. return ( false, 0 ); } /** * Checks if address is on specified winner ranking position. * Used in Lottery, to check if msg.sender is really the * winner #rankingPosition, as he claims to be. */ function minedSelection_isAddressOnWinnerPosition( address addr, uint32 rankingPosition ) external view returns( bool ) { if( rankingPosition >= numberOfWinners ) return false; // Just check if address at "holders" array // index "sortedWinnerIndexes[ position ]" is really the "addr". uint pos = sortedWinnerIndexes[ rankingPosition / 16 ] .indexes[ rankingPosition % 16 ]; return ( holders[ pos ] == addr ); } /** * Returns an array of all winner addresses, sorted by their * ranking position (winner #1 first, #2 second, etc.). */ function minedSelection_getAllWinners() external view returns( address[] memory ) { address[] memory winners = new address[] ( numberOfWinners ); for( uint i = 0; i < numberOfWinners; i++ ) { uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ]; winners[ i ] = holders[ pos ]; } return winners; } /** * Compute the Lottery Active Stage Score of a token holder. * * This function computes the Active Stage (pre-randomization) * player score, and should generally be used to compute player * intermediate scores - while lottery is still active or on * finishing stage, before random random seed is obtained. */ function getPlayerActiveStageScore( address holderAddr ) external view returns( uint playerScore ) { // Copy the Winner Algo Config into memory, to avoid using // 400-gas costing SLOAD every time we need to load something. WinnerAlgorithmConfig memory cfg = algConfig; // Check if holderAddr is a holder at all! if( holders[ holderIndexes[ holderAddr ] ] != holderAddr ) return 0; // Compute the precision-adjusted constant ratio of // referralBonus max score to the player individual max scores. int individualToReferralRatio = ( PRECISION * cfg.maxPlayerScore_refferalBonus ) / ( int( cfg.maxPlayerScore_etherContributed ) + int( cfg.maxPlayerScore_timeFactor ) + int( cfg.maxPlayerScore_tokenHoldingAmount ) ); // Max available player score. int maxAvailablePlayerScore = int( cfg.maxPlayerScore_etherContributed + cfg.maxPlayerScore_timeFactor + cfg.maxPlayerScore_tokenHoldingAmount + cfg.maxPlayerScore_refferalBonus ); // Fix Min-Max scores, to avoid division by zero, if min == max. // If min == max, make the difference equal to 1. MinMaxHolderScores memory minMaxCpy = minMaxScores; MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores; priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy ); // Now, add bonus score, and compute total player's score: // Bonus part, individual score part, and referree score part. int totalPlayerScore = holderData[ holderAddr ].bonusScore + computeHolderIndividualScores( cfg, minMaxCpy, holderData[ holderAddr ] ) + computeReferreeScoresForHolder( individualToReferralRatio, cfg, minMaxRefCpy, holderData[ holderAddr ] ); // Check if total player score <= 0. If so, make it equal // to 1, because otherwise randomization won't be possible. if( totalPlayerScore <= 0 ) totalPlayerScore = 1; // Now, check if it's not more than max! If so, lowerify. // This could have happen'd because of bonus. if( totalPlayerScore > maxAvailablePlayerScore ) totalPlayerScore = maxAvailablePlayerScore; // Return the score! return uint( totalPlayerScore ); } /** * Internal sub-procedure of the function below, used to obtain * a final, randomized score of a Single Holder. */ function priv_getSingleHolderScore( address hold3r, int individualToReferralRatio, int maxAvailablePlayerScore, int SCORE_RAND_FACT, WinnerAlgorithmConfig memory cfg, MinMaxHolderScores memory minMaxCpy, MinMaxReferralScores memory minMaxRefCpy ) internal view returns( uint endScore ) { // Fetch the needed holder data to in-memory hdata variable, // to save gas on score part computing functions. HolderData memory hdata; // Slot 1: hdata.etherContributed = holderData[ hold3r ].etherContributed; hdata.timeFactors = holderData[ hold3r ].timeFactors; hdata.tokenBalance = holderData[ hold3r ].tokenBalance; hdata.referreeCount = holderData[ hold3r ].referreeCount; // Slot 2: hdata.referree_etherContributed = holderData[ hold3r ].referree_etherContributed; hdata.referree_timeFactors = holderData[ hold3r ].referree_timeFactors; hdata.referree_tokenBalance = holderData[ hold3r ].referree_tokenBalance; hdata.bonusScore = holderData[ hold3r ].bonusScore; // Now, add bonus score, and compute total player's score: // Bonus part, individual score part, and referree score part. int totalPlayerScore = hdata.bonusScore + computeHolderIndividualScores( cfg, minMaxCpy, hdata ) + computeReferreeScoresForHolder( individualToReferralRatio, cfg, minMaxRefCpy, hdata ); // Check if total player score <= 0. If so, make it equal // to 1, because otherwise randomization won't be possible. if( totalPlayerScore <= 0 ) totalPlayerScore = 1; // Now, check if it's not more than max! If so, lowerify. // This could have happen'd because of bonus. if( totalPlayerScore > maxAvailablePlayerScore ) totalPlayerScore = maxAvailablePlayerScore; // Multiply the score by the Random Modulo Adjustment // Factor, to get fairer ratio of random-to-determined data. totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) / ( PRECISION ); // Score is computed! // Now, randomize it, and add to Final Scores Array. // We use keccak to generate a random number from random seed, // using holder's address as a nonce. uint modulizedRandomNumber = uint( keccak256( abi.encodePacked( randomSeed, hold3r ) ) ) % RANDOM_MODULO; // Add the random number, to introduce the random factor. // Ratio of (current) totalPlayerScore to modulizedRandomNumber // is the same as ratio of randRatio_scorePart to // randRatio_randPart. return uint( totalPlayerScore ) + modulizedRandomNumber; } /** * Winner Self-Validation algo-type main function. * Here, we compute scores for all lottery holders iteratively * in O(n) time, and thus get the winner ranking position of * the holder in question. * * This function performs essentialy the same steps as the * Mined-variant (executeWinnerSelectionAlgorithm), but doesn't * write anything to blockchain. * * @param holderAddr - address of a holder whose rank we want to find. */ function winnerSelfValidation_getWinnerStatus( address holderAddr ) internal view returns( bool isWinner, uint rankingPosition ) { // Copy the Winner Algo Config into memory, to avoid using // 400-gas costing SLOAD every time we need to load something. WinnerAlgorithmConfig memory cfg = algConfig; // Can only be performed if algorithm is WinnerSelfValidation! require( cfg.endingAlgoType == uint8(Lottery.EndingAlgoType.WinnerSelfValidation)/*, "Algorithm cannot be performed on current Algo-Type!" */); // Check if holderAddr is a holder at all! require( holders[ holderIndexes[ holderAddr ] ] == holderAddr/*, "holderAddr is not a lottery token holder!" */); // Now, we gotta find the winners using a Randomized Score-Based // Winner Selection Algorithm. // // During transfers, all player intermediate scores // (etherContributed, timeFactors, and tokenBalances) were // already set in every holder's HolderData structure, // during operations of updateHolderData_preTransfer() function. // // Minimum and maximum values are also known, so normalization // will be easy. // All referral tree score data were also properly propagated // during operations of updateAndPropagateScoreChanges() function. // // All we block.timestamp have to do, is loop through holder array, and // compute randomized final scores for every holder. // Compute the precision-adjusted constant ratio of // referralBonus max score to the player individual max scores. int individualToReferralRatio = ( PRECISION * cfg.maxPlayerScore_refferalBonus ) / ( int( cfg.maxPlayerScore_etherContributed ) + int( cfg.maxPlayerScore_timeFactor ) + int( cfg.maxPlayerScore_tokenHoldingAmount ) ); // Max available player score. int maxAvailablePlayerScore = int( cfg.maxPlayerScore_etherContributed + cfg.maxPlayerScore_timeFactor + cfg.maxPlayerScore_tokenHoldingAmount + cfg.maxPlayerScore_refferalBonus ); // Random Factor of scores, to maintain random-to-determined // ratio equal to specific value (1:5 for example - // "randPart" == 5/*, "scorePart" */== 1). // // maxAvailablePlayerScore * FACT --- scorePart // RANDOM_MODULO --- randPart // // RANDOM_MODULO * scorePart // maxAvailablePlayerScore * FACT = ------------------------- // randPart // // RANDOM_MODULO * scorePart // FACT = -------------------------------------- // randPart * maxAvailablePlayerScore int SCORE_RAND_FACT = ( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) / ( int(cfg.randRatio_randPart) * maxAvailablePlayerScore ); // Fix Min-Max scores, to avoid division by zero, if min == max. // If min == max, make the difference equal to 1. MinMaxHolderScores memory minMaxCpy = minMaxScores; MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores; priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy ); // How many holders had higher scores than "holderAddr". // Used to obtain the final winner rank of "holderAddr". uint numOfHoldersHigherThan = 0; // The final (randomized) score of "holderAddr". uint holderAddrsFinalScore = priv_getSingleHolderScore( holderAddr, individualToReferralRatio, maxAvailablePlayerScore, SCORE_RAND_FACT, cfg, minMaxCpy, minMaxRefCpy ); // Index of holderAddr. uint holderAddrIndex = holderIndexes[ holderAddr ]; // Loop through all the allowed holders. for( uint i = 0; i < ( holders.length < SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ? holders.length : SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ); i++ ) { // Skip the holderAddr's index. if( i == holderAddrIndex ) continue; // Compute the score using helper function. uint endScore = priv_getSingleHolderScore( holders[ i ], individualToReferralRatio, maxAvailablePlayerScore, SCORE_RAND_FACT, cfg, minMaxCpy, minMaxRefCpy ); // Check if score is higher than HolderAddr's, and if so, check. if( endScore > holderAddrsFinalScore ) numOfHoldersHigherThan++; } // All scores are checked! // Now, we can obtain holderAddr's winner rank based on how // many scores were above holderAddr's score! isWinner = ( numOfHoldersHigherThan < cfg.winnerCount ); rankingPosition = numOfHoldersHigherThan; } /** * Rolled-Randomness algo-type main function. * Here, we only compute the score of the holder in question, * and compare it to maximum-available final score, divided * by no-of-winners. * * @param holderAddr - address of a holder whose rank we want to find. */ function rolledRandomness_getWinnerStatus( address holderAddr ) internal view returns( bool isWinner, uint rankingPosition ) { // Copy the Winner Algo Config into memory, to avoid using // 400-gas costing SLOAD every time we need to load something. WinnerAlgorithmConfig memory cfg = algConfig; // Can only be performed if algorithm is RolledRandomness! require( cfg.endingAlgoType == uint8(Lottery.EndingAlgoType.RolledRandomness)/*, "Algorithm cannot be performed on current Algo-Type!" */); // Check if holderAddr is a holder at all! require( holders[ holderIndexes[ holderAddr ] ] == holderAddr/*, "holderAddr is not a lottery token holder!" */); // Now, we gotta find the winners using a Randomized Score-Based // Winner Selection Algorithm. // // During transfers, all player intermediate scores // (etherContributed, timeFactors, and tokenBalances) were // already set in every holder's HolderData structure, // during operations of updateHolderData_preTransfer() function. // // Minimum and maximum values are also known, so normalization // will be easy. // All referral tree score data were also properly propagated // during operations of updateAndPropagateScoreChanges() function. // // All we block.timestamp have to do, is loop through holder array, and // compute randomized final scores for every holder. // Compute the precision-adjusted constant ratio of // referralBonus max score to the player individual max scores. int individualToReferralRatio = ( PRECISION * cfg.maxPlayerScore_refferalBonus ) / ( int( cfg.maxPlayerScore_etherContributed ) + int( cfg.maxPlayerScore_timeFactor ) + int( cfg.maxPlayerScore_tokenHoldingAmount ) ); // Max available player score. int maxAvailablePlayerScore = int( cfg.maxPlayerScore_etherContributed + cfg.maxPlayerScore_timeFactor + cfg.maxPlayerScore_tokenHoldingAmount + cfg.maxPlayerScore_refferalBonus ); // Random Factor of scores, to maintain random-to-determined // ratio equal to specific value (1:5 for example - // "randPart" == 5, "scorePart" == 1). // // maxAvailablePlayerScore * FACT --- scorePart // RANDOM_MODULO --- randPart // // RANDOM_MODULO * scorePart // maxAvailablePlayerScore * FACT = ------------------------- // randPart // // RANDOM_MODULO * scorePart // FACT = -------------------------------------- // randPart * maxAvailablePlayerScore int SCORE_RAND_FACT = ( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) / ( int(cfg.randRatio_randPart) * maxAvailablePlayerScore ); // Fix Min-Max scores, to avoid division by zero, if min == max. // If min == max, make the difference equal to 1. MinMaxHolderScores memory minMaxCpy = minMaxScores; MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores; priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy ); // The final (randomized) score of "holderAddr". uint holderAddrsFinalScore = priv_getSingleHolderScore( holderAddr, individualToReferralRatio, maxAvailablePlayerScore, SCORE_RAND_FACT, cfg, minMaxCpy, minMaxRefCpy ); // Now, compute the Max-Final-Random Score, divide it // by the Holder Count, and get the ranking by placing this // holder's score in it's corresponding part. // // In this approach, we assume linear randomness distribution. // In practice, distribution might be a bit different, but this // approach is the most efficient. // // Max-Final-Score (randomized) is the highest available score // that can be achieved, and is made by adding together the // maximum availabe Player Score Part and maximum available // Random Part (equals RANDOM_MODULO). // These parts have a ratio equal to config-specified // randRatio_scorePart to randRatio_randPart. // // So, if player's active stage's score is low (1), but rand-part // in ratio is huge, then the score is mostly random, so // maxFinalScore is close to the RANDOM_MODULO - maximum random // value that can be rolled. // // If, however, we use 1:1 playerScore-to-Random Ratio, then // playerScore and RandomScore make up equal parts of end score, // so the maxFinalScore is actually two times larger than // RANDOM_MODULO, so player needs to score more // player-points to get larger prizes. // // In default configuration, playerScore-to-random ratio is 1:3, // so there's a good randomness factor, so even the low-scoring // players can reasonably hope to get larger prizes, but // the higher is player's active stage score, the more // chances of scoring a high final score a player gets, with // the higher-end of player scores basically guaranteeing // themselves a specific prize amount, if winnerCount is // big enough to overlap. int maxRandomPart = int( RANDOM_MODULO - 1 ); int maxPlayerScorePart = ( SCORE_RAND_FACT * maxAvailablePlayerScore ) / PRECISION; uint maxFinalScore = uint( maxRandomPart + maxPlayerScorePart ); // Compute the amount that single-holder's virtual part // might take up in the max-final score. uint singleHolderPart = maxFinalScore / holders.length; // Now, compute how many single-holder-parts are there in // this holder's score. uint holderAddrScorePartCount = holderAddrsFinalScore / singleHolderPart; // The ranking is that number, minus holders length. // If very high score is scored, default to position 0 (highest). rankingPosition = ( holderAddrScorePartCount < holders.length ? holders.length - holderAddrScorePartCount : 0 ); isWinner = ( rankingPosition < cfg.winnerCount ); } /** * Genericized, algorithm type-dependent getWinnerStatus function. */ function getWinnerStatus( address addr ) external view returns( bool isWinner, uint32 rankingPosition ) { bool _isW; uint _rp; if( algConfig.endingAlgoType == uint8(Lottery.EndingAlgoType.RolledRandomness) ) { (_isW, _rp) = rolledRandomness_getWinnerStatus( addr ); return ( _isW, uint32( _rp ) ); } if( algConfig.endingAlgoType == uint8(Lottery.EndingAlgoType.WinnerSelfValidation) ) { (_isW, _rp) = winnerSelfValidation_getWinnerStatus( addr ); return ( _isW, uint32( _rp ) ); } if( algConfig.endingAlgoType == uint8(Lottery.EndingAlgoType.MinedWinnerSelection) ) { (_isW, _rp) = minedSelection_getWinnerStatus( addr ); return ( _isW, uint32( _rp ) ); } } } interface IMainUniLotteryPool { function isLotteryOngoing( address lotAddr ) external view returns( bool ); function scheduledCallback( uint256 requestID ) external; function onLotteryCallbackPriceExceedingGivenFunds( address lottery, uint currentRequestPrice, uint poolGivenPastRequestPrice ) external returns( bool ); } interface ILottery { function finish_randomnessProviderCallback( uint256 randomSeed, uint256 requestID ) external; } contract UniLotteryStorageFactory { // The Pool Address. address payable poolAddress; // The Delegate Logic contract, containing all code for // all LotteryStorage contracts to be deployed. address immutable public delegateContract; // Pool-Only modifier. modifier poolOnly { require( msg.sender == poolAddress/*, "Function can only be called by the Main Pool!" */); _; } // Constructor. // Deploy the Delegate Contract here. // constructor() { delegateContract = address( new LotteryStorage() ); } // Initialization function. // Set the poolAddress as msg.sender, and lock it. function initialize() external { require( poolAddress == address( 0 )/*, "Initialization has already finished!" */); // Set the Pool's Address. poolAddress = msg.sender; } /** * Deploy a new Lottery Storage Stub, to be used by it's corresponding * Lottery Stub, which will be created later, passing this Storage * we create here. * @return newStorage - the Lottery Storage Stub contract just deployed. */ function createNewStorage() public poolOnly returns( address newStorage ) { LotteryStorageStub stub = new LotteryStorageStub(); stub.stub_construct( delegateContract ); return address( stub ); } } abstract contract Context { function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } abstract contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) virtual external; } interface ProvableI { function cbAddress() external returns (address _cbAddress); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string calldata _datasource) external returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string calldata _datasource, uint _gasLimit) external returns (uint _dsprice); function queryN(uint _timestamp, string calldata _datasource, bytes calldata _argN) external payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } interface OracleAddrResolverI { function getAddress() external returns (address _address); } library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return _buffer The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return _buffer The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } contract usingProvable { using CBOR for Buffer.buffer; ProvableI provable; OracleAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string provable_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) provable_randomDS_args; mapping(bytes32 => bool) provable_randomDS_sessionKeysHashVerified; modifier provableAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { provable_setNetwork(networkID_auto); } if (address(provable) != OAR.getAddress()) { provable = ProvableI(OAR.getAddress()); } _; } modifier provable_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName()); require(proofVerified); _; } function provable_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { _networkID; // NOTE: Silence the warning and remain backwards compatible return provable_setNetwork(); } function provable_setNetworkName(string memory _network_name) internal { provable_network_name = _network_name; } function provable_getNetworkName() internal view returns (string memory _networkName) { return provable_network_name; } function provable_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OracleAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); provable_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OracleAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); provable_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OracleAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); provable_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OracleAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); provable_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OracleAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); provable_setNetworkName("eth_goerli"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OracleAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OracleAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OracleAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } /** * @dev The following `__callback` functions are just placeholders ideally * meant to be defined in child contract when proofs are used. * The function bodies simply silence compiler warnings. */ function __callback(bytes32 _myid, string memory _result) virtual public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) virtual public { _myid; _result; _proof; provable_randomDS_args[bytes32(0)] = bytes32(0); } function provable_getPrice(string memory _datasource) provableAPI internal returns (uint _queryPrice) { return provable.getPrice(_datasource); } function provable_getPrice(string memory _datasource, uint _gasLimit) provableAPI internal returns (uint _queryPrice) { return provable.getPrice(_datasource, _gasLimit); } function provable_query(string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return provable.query{value: price}(0, _datasource, _arg); } function provable_query(uint _timestamp, string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return provable.query{value: price}(_timestamp, _datasource, _arg); } function provable_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return provable.query_withGasLimit{value: price}(_timestamp, _datasource, _arg, _gasLimit); } function provable_query(string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return provable.query_withGasLimit{value: price}(0, _datasource, _arg, _gasLimit); } function provable_query(string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return provable.query2{value: price}(0, _datasource, _arg1, _arg2); } function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return provable.query2{value: price}(_timestamp, _datasource, _arg1, _arg2); } function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return provable.query2_withGasLimit{value: price}(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function provable_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return provable.query2_withGasLimit{value: price}(0, _datasource, _arg1, _arg2, _gasLimit); } function provable_query(string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return provable.queryN{value: price}(0, _datasource, args); } function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return provable.queryN{value: price}(_timestamp, _datasource, args); } function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit); } function provable_query(string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit); } function provable_query(string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return provable.queryN{value: price}(0, _datasource, args); } function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return provable.queryN{value: price}(_timestamp, _datasource, args); } function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit); } function provable_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit); } function provable_query(string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_setProof(byte _proofP) provableAPI internal { return provable.setProofType(_proofP); } function provable_cbAddress() provableAPI internal returns (address _callbackAddress) { return provable.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function provable_setCustomGasPrice(uint _gasPrice) provableAPI internal { return provable.setCustomGasPrice(_gasPrice); } function provable_randomDS_getSessionPubKeyHash() provableAPI internal returns (bytes32 _sessionKeyHash) { return provable.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function provable_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = provable_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number(), 1)), xor(coinbase(), timestamp()))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = provable_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } provable_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function provable_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { provable_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function provable_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function provable_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function provable_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (provable_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete provable_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = provable_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { /*assembly { let fmem := mload(0x40) codecopy(fmem, codesize(), sub(msize(), fmem)) }*/ } } interface IUniswapPair is IERC20 { // Addresses of the first and second pool-kens. function token0() external view returns (address); function token1() external view returns (address); // Get the pair's token pool reserves. function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } contract UniLotteryPool is ERC20, CoreUniLotterySettings { // =================== Structs & Enums =================== // /* Lottery running mode (Auto-Lottery, manual lottery). * * If Auto-Lottery feature is enabled, the new lotteries will start * automatically after the previous one finished, and will use * the default, agreed-upon config, which is set by voting. * * If Manual Lottery is enabled, the new lotteries are started * manually, by submitting and voting for a specific config. * * Both modes can have AVERAGE_CONFIG feature, when final lottery * config is not set by voting for one of several user-submitted * configs, but final config is computed by averaging all the voted * configs, where each vote proposes a config. */ enum LotteryRunMode { MANUAL, AUTO, MANUAL_AVERAGE_CONFIG, AUTO_AVERAGE_CONFIG } // =================== Events =================== // // Periodic stats event. event PoolStats( uint32 indexed lotteriesPerformed, uint indexed totalPoolFunds, uint indexed currentPoolBalance ); // New poolholder joins and complete withdraws of a poolholder. event NewPoolholderJoin( address indexed poolholder, uint256 initialAmount ); event PoolholderWithdraw( address indexed poolholder ); // Current poolholder liquidity adds/removes. event AddedLiquidity( address indexed poolholder, uint256 indexed amount ); event RemovedLiquidity( address indexed poolholder, uint256 indexed amount ); // Lottery Run Mode change (for example, from Manual to Auto lottery). event LotteryRunModeChanged( LotteryRunMode previousMode, LotteryRunMode newMode ); // Lottery configs proposed. In other words, it's a new lottery start // initiation. If no config specified, then the default config for // that lottery is used. event NewConfigProposed( address indexed initiator, Lottery.LotteryConfig cfg, uint configIndex ); // Lottery started. event LotteryStarted( address indexed lottery, uint256 indexed fundsUsed, uint256 indexed poolPercentageUsed, Lottery.LotteryConfig config ); // Lottery finished. event LotteryFinished( address indexed lottery, uint256 indexed totalReturn, uint256 indexed profitAmount ); // Ether transfered into the fallback receive function. event EtherReceived( address indexed sender, uint256 indexed value ); // ========= Constants ========= // // The Core Constants (OWNER_ADDRESS, Owner's max profit amount), // and also the percentage calculation-related constants, // are defined in the CoreUniLotterySettings contract, which this // contract inherits from. // ERC-20 token's public constants. string constant public name = "UniLottery Main Pool"; string constant public symbol = "ULPT"; uint256 constant public decimals = 18; // ========= State variables ========= // // --------- Slot --------- // // The debt to the Randomness Provider. // Incurred when we allow the Randomness Provider to execute // requests with higher price than we have given it funds for. // (of course, executed only when the Provider has enough balance // to execute it). // Paid back on next Randomness Provider request. uint80 randomnessProviderDebt; // Auto-Mode lottery parameters: uint32 public autoMode_nextLotteryDelay = 1 days; uint16 public autoMode_maxNumberOfRuns = 50; // When the last Auto-Mode lottery was started. uint32 public autoMode_lastLotteryStarted; // When the last Auto-Mode lottery has finished. // Used to compute the time until the next lottery. uint32 public autoMode_lastLotteryFinished; // Auto-Mode callback scheduled time. uint32 public autoMode_timeCallbackScheduled; // Iterations of current Auto-Lottery cycle. uint16 autoMode_currentCycleIterations = 0; // Is an Auto-Mode lottery currently ongoing? bool public autoMode_isLotteryCurrentlyOngoing = false; // Re-Entrancy Lock for Liquidity Provide/Remove functions. bool reEntrancyLock_Locked; // --------- Slot --------- // // The initial funds of all currently active lotteries. uint currentLotteryFunds; // --------- Slot --------- // // Most recently launched lottery. Lottery public mostRecentLottery; // Current lottery run-mode (Enum, so 1 byte). LotteryRunMode public lotteryRunMode = LotteryRunMode.MANUAL; // Last time when funds were manually sent to the Randomness Provider. uint32 lastTimeRandomFundsSend; // --------- Slot --------- // // The address of the Gas Oracle (our own service which calls our // gas price update function periodically). address gasOracleAddress; // --------- Slot --------- // // Stores all lotteries that have been performed // (including currently ongoing ones ). Lottery[] public allLotteriesPerformed; // --------- Slot --------- // // Currently ongoing lotteries - a list, and a mapping. mapping( address => bool ) ongoingLotteries; // --------- Slot --------- // // Owner-approved addresses, which can call functions, marked with // modifier "ownerApprovedAddressOnly", on behalf of the Owner, // to initiate Owner-Only operations, such as setting next lottery // config, or moving specified part of Owner's liquidity pool share to // Owner's wallet address. // Note that this is equivalent of as if Owner had called the // removeLiquidity() function from OWNER_ADDRESS. // // These owner-approved addresses, able to call owner-only functions, // are used by Owner, to minimize risk of a hack in these ways: // - OWNER_ADDRESS wallet, which might hold significant ETH amounts, // is used minimally, to have as little log-on risk in Metamask, // as possible. // - The approved addresses can have very little Ether, so little // risk of using them from Metamask. // - Periodic liquidity removes from the Pool can help to reduce // losses, if Pool contract was hacked (which most likely // wouldn't ever happen given our security measures, but // better be safe than sorry). // mapping( address => bool ) public ownerApprovedAddresses; // --------- Slot --------- // // The config to use for the next lottery that will be started. Lottery.LotteryConfig internal nextLotteryConfig; // --------- Slot --------- // // Randomness Provider address. UniLotteryRandomnessProvider immutable public randomnessProvider; // --------- Slot --------- // // The Lottery Factory that we're using to deploy NEW lotteries. UniLotteryLotteryFactory immutable public lotteryFactory; // --------- Slot --------- // // The Lottery Storage factory that we're using to deploy // new lottery storages. Used inside a Lottery Factory. address immutable public storageFactory; // ========= FUNCTIONS - METHODS ========= // // ========= Private Functions ========= // // Owner-Only modifier (standard). modifier ownerOnly { require( msg.sender == OWNER_ADDRESS/*, "Function is Owner-Only!" */); _; } // Owner, or Owner-Approved address only. modifier ownerApprovedAddressOnly { require( ownerApprovedAddresses[ msg.sender ]/*, "Function can be called only by Owner-Approved addresses!"*/); _; } // Owner Approved addresses, and the Gas Oracle address. // Used when updating RandProv's gas price. modifier gasOracleAndOwnerApproved { require( ownerApprovedAddresses[ msg.sender ] || msg.sender == gasOracleAddress/*, "Function can only be called by Owner-Approved addrs, " "and by the Gas Oracle!" */); _; } // Randomness Provider-Only modifier. modifier randomnessProviderOnly { require( msg.sender == address( randomnessProvider )/*, "Function can be called only by the Randomness Provider!" */); _; } /** * Modifier for checking if a caller is a currently ongoing * lottery - that is, if msg.sender is one of addresses in * ongoingLotteryList array, and present in ongoingLotteries. */ modifier calledByOngoingLotteryOnly { require( ongoingLotteries[ msg.sender ]/*, "Function can be called only by ongoing lotteries!"*/); _; } /** * Lock the function to protect from re-entrancy, using * a Re-Entrancy Mutex Lock. */ modifier mutexLOCKED { require( ! reEntrancyLock_Locked/*, "Re-Entrant Call Detected!" */); reEntrancyLock_Locked = true; _; reEntrancyLock_Locked = false; } // Emits a statistical event, summarizing current pool state. function emitPoolStats() private { (uint32 a, uint b, uint c) = getPoolStats(); emit PoolStats( a, b, c ); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Launch a new UniLottery Lottery, from specified Lottery Config. * Perform all initialization procedures, including initial fund * transfer, and random provider registration. * * @return newlyLaunchedLottery - the Contract instance (address) of * the newly deployed and initialized lottery. */ function launchLottery( Lottery.LotteryConfig memory cfg ) private mutexLOCKED returns( Lottery newlyLaunchedLottery ) { // Check config fund requirement. // Lottery will need funds equal to: // initial funds + gas required for randomness prov. callback. // Now, get the price of the random datasource query with // the above amount of callback gas, from randomness provider. uint callbackPrice = randomnessProvider .getPriceForRandomnessCallback( LOTTERY_RAND_CALLBACK_GAS ); // Also take into account the debt that we might owe to the // Randomness Provider, if it previously executed requests // with price being higher than we have gave it funds for. // // This situation can occur because we transfer lottery callback // price funds before lottery starts, and when that lottery // finishes (which can happen after several weeks), then // the gas price might be higher than we have estimated // and given funds for on lottery start. // In this scenario, Randomness Provider would execute the // request nonetheless, provided that it has enough funds in // it's balance, to execute it. // // However, the Randomness Provider would notify us, that a // debt of X ethers have been incurred, so we would have // to transfer that debt's amount with next request's funds // to Randomness Provider - and that's precisely what we // are doing here, block.timestamp: // Compute total cost of this lottery - initial funds, // Randomness Provider callback cost, and debt from previous // callback executions. uint totalCost = cfg.initialFunds + callbackPrice + randomnessProviderDebt; // Check if our balance is enough to pay the cost. // TODO: Implement more robust checks on minimum and maximum // allowed fund restrictions. require( totalCost <= address( this ).balance/*, "Insufficient funds for this lottery start!" */); // Deploy the new lottery contract using Factory. Lottery lottery = Lottery( lotteryFactory.createNewLottery( cfg, address( randomnessProvider ) ) ); // Check if the lottery's pool address and owner address // are valid (same as ours). require( lottery.poolAddress() == address( this ) && lottery.OWNER_ADDRESS() == OWNER_ADDRESS/*, "Lottery's pool or owner addresses are invalid!" */); // Transfer the Gas required for lottery end callback, and the // debt (if some exists), into the Randomness Provider. address( randomnessProvider ).transfer( callbackPrice + randomnessProviderDebt ); // Clear the debt (if some existed) - it has been paid. randomnessProviderDebt = 0; // Notify the Randomness Provider about how much gas will be // needed to run this lottery's ending callback, and how much // funds we have given for it. randomnessProvider.setLotteryCallbackGas( address( lottery ), LOTTERY_RAND_CALLBACK_GAS, uint160( callbackPrice ) ); // Initialize the lottery - start the active lottery stage! // Send initial funds to the lottery too. lottery.initialize{ value: cfg.initialFunds }(); // Lottery was successfully initialized! // Now, add it to tracking arrays, and emit events. ongoingLotteries[ address(lottery) ] = true; allLotteriesPerformed.push( lottery ); // Set is as the Most Recently Launched Lottery. mostRecentLottery = lottery; // Update current lottery funds. currentLotteryFunds += cfg.initialFunds; // Emit the apppproppppriate evenc. emit LotteryStarted( address( lottery ), cfg.initialFunds, ( (_100PERCENT) * totalCost ) / totalPoolFunds(), cfg ); // Return the newly-successfully-started lottery. return lottery; } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * When AUTO run-mode is set, this function schedules a new lottery * to be started after the last Auto-Mode lottery has ended, after * a specific time delay (by default, 1 day delay). * * Also, it's used to bootstrap the Auto-Mode loop - because * it schedules a callback to get called. * * This function is called in 2 occasions: * * 1. When lotteryFinish() detects an AUTO run-mode, and so, a * new Auto-Mode iteration needs to be performed. * * 2. When external actor bootstraps a new Auto-Mode cycle. * * Notice, that this function doesn't use require()'s - that's * because it's getting called from lotteryFinish() too, and * we don't want that function to fail just because some user * set run mode to other value than AUTO during the time before. * The only require() is when we check for re-entrancy. * * How Auto-Mode works? * Everything is based on the Randomness Provider scheduled callback * functionality, which is in turn based on Provable services. * Basically, here we just schedule a scheduledCallback() to * get called after a specified amount of time, and the * scheduledCallback() performs the new lottery launch from the * current next-lottery config. * * * What's payable? * - We send funds to Randomness Provider, required to launch * our callback later. */ function scheduleAutoModeCallback() private mutexLOCKED returns( bool success ) { // Firstly, check if mode is AUTO. if( lotteryRunMode != LotteryRunMode.AUTO ) { autoMode_currentCycleIterations = 0; return false; } // Start a scheduled callback using the Randomness Provider // service! But first, we gotta transfer the needed funds // to the Provider. // Get the price. uint callbackPrice = randomnessProvider .getPriceForScheduledCallback( AUTO_MODE_SCHEDULED_CALLBACK_GAS ); // Add the debt, if exists. uint totalPrice = callbackPrice + randomnessProviderDebt; if( totalPrice > address(this).balance ) { return false; } // Send the required funds to the Rand.Provider. // Use the send() function, because it returns false upon failure, // and doesn't revert this transaction. if( ! address( randomnessProvider ).send( totalPrice ) ) { return false; } // Now, we've just paid the debt (if some existed). randomnessProviderDebt = 0; // Now, call the scheduling function of the Randomness Provider! randomnessProvider.schedulePoolCallback( autoMode_nextLotteryDelay, AUTO_MODE_SCHEDULED_CALLBACK_GAS, callbackPrice ); // Set the time the callback was scheduled. autoMode_timeCallbackScheduled = uint32( block.timestamp ); return true; } // ========= Public Functions ========= // /** * Constructor. * - Here, we deploy the ULPT token contract. * - Also, we deploy the Provable-powered Randomness Provider * contract, which lotteries will use to get random seed. * - We assign our Lottery Factory contract address to the passed * parameter - the Lottery Factory contract which was deployed * before, but not yet initialize()'d. * * Notice, that the msg.sender (the address who deployed the pool * contract), doesn't play any special role in this nor any related * contracts. */ constructor( address _lotteryFactoryAddr, address _storageFactoryAddr, address payable _randProvAddr ) { // Initialize the randomness provider. UniLotteryRandomnessProvider( _randProvAddr ).initialize(); randomnessProvider = UniLotteryRandomnessProvider( _randProvAddr ); // Set the Lottery Factory contract address, and initialize it! UniLotteryLotteryFactory _lotteryFactory = UniLotteryLotteryFactory( _lotteryFactoryAddr ); // Initialize the lottery factory, setting it to use the // specified Storage Factory. // After this point, factory states become immutable. _lotteryFactory.initialize( _storageFactoryAddr ); // Assign the Storage Factory address. // Set the immutable variables to their temporary placeholders. storageFactory = _storageFactoryAddr; lotteryFactory = _lotteryFactory; // Set the first Owner-Approved address as the OWNER_ADDRESS // itself. ownerApprovedAddresses[ OWNER_ADDRESS ] = true; } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< * * The "Receive Ether" function. * Used to receive Ether from Lotteries, and from the * Randomness Provider, when retrieving funds. */ receive() external payable { emit EtherReceived( msg.sender, msg.value ); } /** * Get total funds of the pool -- the pool balance, and all the * initial funds of every currently-ongoing lottery. */ function totalPoolFunds() public view returns( uint256 ) { // Get All Active Lotteries initial funds. /*uint lotteryBalances = 0; for( uint i = 0; i < ongoingLotteryList.length; i++ ) { lotteryBalances += ongoingLotteryList[ i ].getActiveInitialFunds(); }*/ return address(this).balance + currentLotteryFunds; } /** * Get current pool stats - number of poolholders, * number of voters, etc. */ function getPoolStats() public view returns( uint32 _numberOfLotteriesPerformed, uint _totalPoolFunds, uint _currentPoolBalance ) { _numberOfLotteriesPerformed = uint32( allLotteriesPerformed.length ); _totalPoolFunds = totalPoolFunds(); _currentPoolBalance = address( this ).balance; } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< * * Provide liquidity into the pool, and become a pool shareholder. * - Function accepts Ether payments (No minimum deposit), * and mints a proportionate number of ULPT tokens for the * sender. */ function provideLiquidity() external payable ownerApprovedAddressOnly mutexLOCKED { // Check for minimum deposit. //require( msg.value > MIN_DEPOSIT/*, "Deposit amount too low!" */); // Compute the pool share that the user should obtain with // the amount he paid in this message -- that is, compute // percentage of the total pool funds (with new liquidity // added), relative to the ether transferred in this msg. // TotalFunds can't be zero, because currently transfered // msg.value is already added to totalFunds. // // Also/*, "percentage" */can't exceed 100%, because condition // "totalPoolFunds() >= msg.value" is ALWAYS true, because // msg.value is already added to totalPoolFunds before // execution of this function's body - transfers to // "payable" functions are executed before the function's // body executes (Solidity docs). // uint percentage = ( (_100PERCENT) * msg.value ) / ( totalPoolFunds() ); // Now, compute the amount of new ULPT tokens (x) to mint // for this new liquidity provided, according to formula, // whose explanation is provided below. // // Here, we assume variables: // // uintFormatPercentage: the "percentage" Solidity variable, // defined above, in (uint percentage = ...) statement. // // x: the amount of ULPT tokens to mint for this liquidity // provider, to maintain "percentage" ratio with the // ULPT's totalSupply after minting (newTotalSupply). // // totalSupply: ULPT token's current total supply // (as returned from totalSupply() function). // // Let's start the formula: // // ratio = uintFormatPercentage / (_100PERCENT) // newTotalSupply = totalSupply + x // // x / newTotalSupply = ratio // x / (totalSupply + x) = ratio // x = ratio * (totalSupply + x) // x = (ratio * totalSupply) + (ratio * x) // x - (ratio * x) = (ratio * totalSupply) // (1 * x) - (ratio * x) = (ratio * totalSupply) // ( 1 - ratio ) * x = (ratio * totalSupply) // x = (ratio * totalSupply) / ( 1 - ratio ) // // ratio * totalSupply // x = ------------------------------------------------ // 1 - ( uintFormatPercentage / (_100PERCENT) ) // // // ratio * totalSupply * (_100PERCENT) // x = --------------------------------------------------------------- // ( 1 - (uintFormatPercentage / (_100PERCENT)) )*(_100PERCENT) // // Let's abbreviate "_100PERCENT" to "100%". // // ratio * totalSupply * 100% // x = --------------------------------------------------------- // ( 1 * 100% ) - ( uintFormatPercentage / (100%) ) * (100%) // // ratio * totalSupply * 100% // x = ------------------------------------- // 100% - uintFormatPercentage // // (uintFormatPercentage / (100%)) * totalSupply * 100% // x = ------------------------------------------------------- // 100% - uintFormatPercentage // // (uintFormatPercentage / (100%)) * 100% * totalSupply // x = ------------------------------------------------------- // 100% - uintFormatPercentage // // uintFormatPercentage * totalSupply // x = ------------------------------------ // 100% - uintFormatPercentage // // So, with our Solidity variables, that would be: // ==================================================== // // // // percentage * totalSupply // // amountToMint = ------------------------------ // // (_100PERCENT) - percentage // // // // ==================================================== // // // We know that "percentage" is ALWAYS <= 100%, because // msg.value is already added to address(this).balance before // the payable function's body executes. // // However, notice that when "percentage" approaches 100%, // the denominator approaches 0, and that's not good. // // So, we must ensure that uint256 precision is enough to // handle such situations, and assign a "default" value for // amountToMint if such situation occurs. // // The most prominent case when this situation occurs, is on // the first-ever liquidity provide, when ULPT total supply is // zero, and the "percentage" value is 100%, because pool's // balance was 0 before the operation. // // In such situation, we mint the 100 initial ULPT, which // represent the pool share of the first ever pool liquidity // provider, and that's 100% of the pool. // // Also, we do the same thing (mint 100 ULPT tokens), on all // on all other situations when "percentage" is too close to 100%, // such as when there's a very tiny amount of liquidity left in // the pool. // // We check for those conditions based on precision of uint256 // number type. // We know, that 256-bit uint can store up to roughly 10^74 // base-10 values. // // Also, in our formula: // "totalSupply" can go to max. 10^30 (in extreme cases). // "percentage" up to 10^12 (with more-than-enough precision). // // When multiplied, that's still only 10^(30+12) = 10^42 , // and that's still a long way to go to 10^74. // // So, the denominator "(_100PERCENT) - percentage" can go down // to 1 safely, we must only ensure that it's not zero - // and the uint256 type will take care of all precision needed. // if( balanceOf( msg.sender ) == 0 ) emit NewPoolholderJoin( msg.sender, msg.value ); // If percentage is below 100%, and totalSupply is NOT ZERO, // work with the above formula. if( percentage < (_100PERCENT) && totalSupply() != 0 ) { // Compute the formula! uint256 amountToMint = ( percentage * totalSupply() ) / ( (_100PERCENT) - percentage ); // Mint the computed amount. _mint( msg.sender, amountToMint ); } // Else, if the newly-added liquidity percentage is 100% // (pool's balance was Zero before this liquidity provide), then // just mint the initial 100 pool tokens. else { _mint( msg.sender, ( 100 * (uint( 10 ) ** decimals) ) ); } // Emit corresponding event, that liquidity has been added. emit AddedLiquidity( msg.sender, msg.value ); emitPoolStats(); } /** * Get the current pool share (percentage) of a specified * address. Return the percentage, compute from ULPT data. */ function getPoolSharePercentage( address holder ) public view returns ( uint percentage ) { return ( (_100PERCENT) * balanceOf( holder ) ) / totalSupply(); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Remove msg.sender's pool liquidity share, and transfer it * back to msg.sender's wallet. * Burn the ULPT tokens that represented msg.sender's share * of the pool. * Notice that no activelyManaged modifier is present, which * means that users are able to withdraw their money anytime. * * However, there's a caveat - if some lotteries are currently * ongoing, the pool's current reserve balance might not be * enough to meet every withdrawer's needs. * * In such scenario, withdrawers have either have to (OR'd): * - Wait for ongoing lotteries to finish and return their * funds back to the pool, * - TODO: Vote for forceful termination of lotteries * (vote can be done whether pool is active or not). * - TODO: Wait for OWNER to forcefully terminate lotteries. * * Notice that last 2 options aren't going to be implemented * in this version, because, as the OWNER is going to be the * only pool shareholder in the begginning, lottery participants * might see the forceful termination feature as an exit-scam * threat, and this would damage project's reputation. * * The feature is going to be implemented in later versions, * after security audits pass, pool is open to public, * and a significant amount of wallets join a pool. */ function removeLiquidity( uint256 ulptAmount ) external ownerApprovedAddressOnly mutexLOCKED { // Find out the real liquidity owner of this call - // Check if the msg.sender is an approved-address, which can // call this function on behalf of the true liquidity owner. // Currently, this feature is only supported for OWNER_ADDRESS. address payable liquidityOwner = OWNER_ADDRESS; // Condition "balanceOf( liquidityOwner ) > 1" automatically // checks if totalSupply() of ULPT is not zero, so we don't have // to check it separately. require( balanceOf( liquidityOwner ) > 1 && ulptAmount != 0 && ulptAmount <= balanceOf( liquidityOwner )/*, "Specified ULPT token amount is invalid!" */); // Now, compute share percentage, and send the appropriate // amount of Ether from pool's balance to liquidityOwner. uint256 percentage = ( (_100PERCENT) * ulptAmount ) / totalSupply(); uint256 shareAmount = ( totalPoolFunds() * percentage ) / (_100PERCENT); require( shareAmount <= address( this ).balance/*, "Insufficient pool contract balance!" */); // Burn the specified amount of ULPT, thus removing the // holder's pool share. _burn( liquidityOwner, ulptAmount ); // Transfer holder's fund share as ether to holder's wallet. liquidityOwner.transfer( shareAmount ); // Emit appropriate events. if( balanceOf( liquidityOwner ) == 0 ) emit PoolholderWithdraw( liquidityOwner ); emit RemovedLiquidity( liquidityOwner, shareAmount ); emitPoolStats(); } // ======== Lottery Management Section ======== // // Check if lottery is currently ongoing. function isLotteryOngoing( address lotAddr ) external view returns( bool ) { return ongoingLotteries[ lotAddr ]; } // Get length of all lotteries performed. function allLotteriesPerformed_length() external view returns( uint ) { return allLotteriesPerformed.length; } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< * * Ongoing (not-yet-completed) lottery finalization function. * - This function is called by a currently ongoing lottery, to * notify the pool about it's finishing. * - After lottery calls this function, lottery is removed from * ongoing lottery tracking list, and set to inactive. * * * Ether is transfered into our contract: * Lottery transfers the pool profit share and initial funds * back to the pool when calling this function, so the */ function lotteryFinish( uint totalReturn, uint profitAmount ) external payable calledByOngoingLotteryOnly { // "De-activate" this lottery. //ongoingLotteries[ msg.sender ] = false; delete ongoingLotteries[ msg.sender ]; // implies "false" // We assume that totalReturn and profitAmount are valid, // because this function can be called only by Lottery, which // was deployed by us before. // Update current lottery funds - this one is no longer active, // so it's funds block.timestamp have been transfered to us. uint lotFunds = Lottery( msg.sender ).getInitialFunds(); if( lotFunds < currentLotteryFunds ) currentLotteryFunds -= lotFunds; else currentLotteryFunds = 0; // Emit approppriate events. emit LotteryFinished( msg.sender, totalReturn, profitAmount ); // If AUTO-MODE is currently set, schedule a next lottery // start using the current AUTO-MODE parameters! // Ignore the return value, because AUTO-MODE params might be // invalid, and we don't want our finish function to fail // just because of that. if( lotteryRunMode == LotteryRunMode.AUTO ) { autoMode_isLotteryCurrentlyOngoing = false; autoMode_lastLotteryFinished = uint32( block.timestamp ); scheduleAutoModeCallback(); } } /** * The Callback function which Randomness Provider will call * when executing the Scheduled Callback requests. * * We use this callback for scheduling Auto-Mode lotteries - * when one lottery finishes, another one is scheduled to run * after specified amount of time. * * In this callback, we start the scheduled Auto-Mode lottery. */ function scheduledCallback( uint256 /*requestID*/ ) public { // At first, check if mode is AUTO (not changed). if( lotteryRunMode != LotteryRunMode.AUTO ) return; // Check if we're not X-Ceeding the number of auto-iterations. if( autoMode_currentCycleIterations >= autoMode_maxNumberOfRuns ) { autoMode_currentCycleIterations = 0; return; } // Launch an auto-lottery using the currently set next // lottery config! // When this lottery finishes, and the mode is still AUTO, // one more lottery will be started. launchLottery( nextLotteryConfig ); // Set the time started, and increment iterations. autoMode_isLotteryCurrentlyOngoing = true; autoMode_lastLotteryStarted = uint32( block.timestamp ); autoMode_currentCycleIterations++; } /** * The Randomness Provider-callable function, which is used to * ask pool for permission to execute lottery ending callback * request with higher price than the pool-given funds for that * specific lottery's ending request, when lottery was created. * * The function notifies the pool about the new and * before-expected price, so the pool could compute a debt to * be paid to the Randomnes Provider in next request. * * Here, we update our debt variable, which is the difference * between current and expected-before request price, * and we'll transfer the debt to Randomness Provider on next * request to Randomness Provider. * * Notice, that we'll permit the execution of the lottery * ending callback only if the new price is not more than * 1.5x higher than before-expected price. * * This is designed so, because the Randomness Provider will * call this function only if it has enough funds to execute the * callback request, and just that the funds that we have transfered * for this specific lottery's ending callback before, are lower * than the current price of execution. * * Why is this the issue? * Lottery can last for several weeks, and we give the callback * execution funds for that specific lottery to Randomness Provider * only on that lottery's initialization. * So, after a few weeks, the Provable services might change the * gas & fee prices, so the callback execution request price * might change. */ function onLotteryCallbackPriceExceedingGivenFunds( address /*lottery*/, uint currentRequestPrice, uint poolGivenExpectedRequestPrice ) external randomnessProviderOnly returns( bool callbackExecutionPermitted ) { require( currentRequestPrice > poolGivenExpectedRequestPrice ); uint difference = currentRequestPrice - poolGivenExpectedRequestPrice; // Check if the price difference is not bigger than the half // of the before-expected pool-given price. // Also, make sure that whole debt doesn't exceed 0.5 ETH. if( difference <= ( poolGivenExpectedRequestPrice / 2 ) && ( randomnessProviderDebt + difference ) < ( (1 ether) / 2 ) ) { // Update our debt, to pay back the difference later, // when we transfer funds for the next request. randomnessProviderDebt += uint80( difference ); // Return true - the callback request execution is permitted. return true; } // The price difference is higher - deny the execution. return false; } // Below are the Owner-Callable voting-skipping functions, to set // the next lottery config, lottery run mode, and other settings. // // When the final version is released, these functions will // be removed, and every governance operation will be done // through voting. /** * Set the LotteryConfig to be used by the next lottery. * Owner-only callable. */ function setNextLotteryConfig( Lottery.LotteryConfig memory cfg ) public ownerApprovedAddressOnly { nextLotteryConfig = cfg; emit NewConfigProposed( msg.sender, cfg, 0 ); // emitPoolStats(); } /** * Set the Lottery Run Mode to be used for further lotteries. * It can be AUTO, or MANUAL (more about it on their descriptions). */ function setRunMode( LotteryRunMode runMode ) external ownerApprovedAddressOnly { // Check if it's one of allowed run modes. require( runMode == LotteryRunMode.AUTO || runMode == LotteryRunMode.MANUAL/*, "This Run Mode is not allowed in current state!" */); // Emit a change event, with old value and new value. emit LotteryRunModeChanged( lotteryRunMode, runMode ); // Set the new run mode! lotteryRunMode = runMode; // emitPoolStats(); } /** * Start a manual mode lottery from the previously set up * next lottery config! */ function startManualModeLottery() external ownerApprovedAddressOnly { // Check if config is set - just check if initial funds // are a valid value. require( nextLotteryConfig.initialFunds != 0/*, "Currently set next-lottery-config is invalid!" */); // Launch a lottery using our private launcher function! launchLottery( nextLotteryConfig ); emitPoolStats(); } /** * Set an Auto-Mode lottery run mode parameters. * The auto-mode is implemented using Randomness Provider * scheduled callback functionality, to schedule a lottery start * on specific intervals. * * @param nextLotteryDelay - amount of time, in seconds, to wait * when last lottery finishes, to start the next lottery. * * @param maxNumberOfRuns - max number of lottery runs in this * Auto-Mode cycle. When it's reached, mode will switch to * MANUAL automatically. */ function setAutoModeParameters( uint32 nextLotteryDelay, uint16 maxNumberOfRuns ) external ownerApprovedAddressOnly { // Set params! autoMode_nextLotteryDelay = nextLotteryDelay; autoMode_maxNumberOfRuns = maxNumberOfRuns; // emitPoolStats(); } /** * Starts an Auto-Mode lottery running cycle with currently * specified Auto-Mode parameters. * Notice that we must be on Auto run-mode currently. */ function startAutoModeCycle() external ownerApprovedAddressOnly { // Check that we're on the Auto-Mode block.timestamp. require( lotteryRunMode == LotteryRunMode.AUTO/*, "Current Run Mode is not AUTO!" */); // Check if valid AutoMode params were specified. require( autoMode_maxNumberOfRuns != 0/*, "Invalid Auto-Mode params set!" */); // Reset the cycle iteration counter. autoMode_currentCycleIterations = 0; // Start the Auto-Mode cycle using a scheduled callback! scheduledCallback( 0 ); // emitPoolStats(); } /** * Set or Remove Owner-approved addresses. * These addresses are used to call ownerOnly functions on behalf * of the OWNER_ADDRESS (more detailed description above). */ function owner_setOwnerApprovedAddress( address addr ) external ownerOnly { ownerApprovedAddresses[ addr ] = true; } function owner_removeOwnerApprovedAddress( address addr ) external ownerOnly { delete ownerApprovedAddresses[ addr ]; } /** * ABIEncoderV2 - compatible getter for the nextLotteryConfig, * which will be retuned as byte array internally, then internally * de-serialized on receive. */ function getNextLotteryConfig() external view returns( Lottery.LotteryConfig memory ) { return nextLotteryConfig; } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< * * Retrieve the UnClaimed Prizes of a completed lottery, if * that lottery's prize claim deadline has already passed. * * - What's payable? This function causes a specific Lottery to * transfer Ether from it's contract balance, to our contract. */ function retrieveUnclaimedLotteryPrizes( address payable lottery ) external ownerApprovedAddressOnly mutexLOCKED { // Just call that function - if the deadline hasn't passed yet, // that function will revert. Lottery( lottery ).getUnclaimedPrizes(); } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< * * Retrieve the specified amount of funds from the Randomness * Provider. * * WARNING: Future scheduled operations on randomness provider * might FAIL if randomness provider won't have enough * funds to execute that operation on that time! * * - What's payable? This function causes the Randomness Provider to * transfer Ether from it's contract balance, to our contract. */ function retrieveRandomnessProviderFunds( uint etherAmount ) external ownerApprovedAddressOnly mutexLOCKED { randomnessProvider.sendFundsToPool( etherAmount ); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Send specific amount of funds to Randomness Provider, from * our contract's balance. * This is useful in cases when gas prices change, and current * funds inside randomness provider are not enough to execute * operations on the new gas cost. * * This operation is limited to 6 ethers once in 12 hours. * * - What's payable? We send Ether to the randomness provider. */ function provideRandomnessProviderFunds( uint etherAmount ) external ownerApprovedAddressOnly mutexLOCKED { // Check if conditions apply! require( ( etherAmount <= 6 ether ) && ( block.timestamp - lastTimeRandomFundsSend > 12 hours )/*, "Random Fund Provide Conditions are not satisfied!" */); // Set the last-time-funds-sent timestamp to block.timestamp. lastTimeRandomFundsSend = uint32( block.timestamp ); // Transfer the funds. address( randomnessProvider ).transfer( etherAmount ); } /** * Set the Gas Price to use in the Randomness Provider. * Used when very volatile gas prices are present during network * congestions, when default is not enough. */ function setGasPriceOfRandomnessProvider( uint gasPrice ) external gasOracleAndOwnerApproved { randomnessProvider.setGasPrice( gasPrice ); } /** * Set the address of the so-called Gas Oracle, which is an * automated script running on our server, and fetching gas prices. * * The address used by this script should be able to call * ONLY the "setGasPriceOfRandomnessProvider" function (above). * * Here, we set that address. */ function setGasOracleAddress( address addr ) external ownerApprovedAddressOnly { gasOracleAddress = addr; } } contract Lottery is ERC20, CoreUniLotterySettings { // ===================== Events ===================== // // After initialize() function finishes. event LotteryInitialized(); // Emitted when lottery active stage ends (Mining Stage starts), // on Mining Stage Step 1, after transferring profits to their // respective owners (pool and OWNER_ADDRESS). event LotteryEnd( uint128 totalReturn, uint128 profitAmount ); // Emitted when on final finish, we call Randomness Provider // to callback us with random value. event RandomnessProviderCalled(); // Requirements for finishing stage start have been reached - // finishing stage has started. event FinishingStageStarted(); // We were currently on the finishing stage, but some requirement // is no longer met. We must stop the finishing stage. event FinishingStageStopped(); // New Referral ID has been generated. event ReferralIDGenerated( address referrer, uint256 id ); // New referral has been registered with a valid referral ID. event ReferralRegistered( address referree, address referrer, uint256 id ); // Fallback funds received. event FallbackEtherReceiver( address sender, uint value ); // ====================== Structs & Enums ====================== // // Lottery Stages. // Described in more detail above, on contract's main doc. enum STAGE { // Initial stage - before the initialize() function is called. INITIAL, // Active Stage: On this stage, all token trading occurs. ACTIVE, // Finishing stage: // This is when all finishing criteria are met, and for every // transfer, we're rolling a pseudo-random number to determine // if we should end the lottery (move to Ending stage). FINISHING, // Ending - Mining Stage: // This stage starts after we lottery is no longer active, // finishing stage ends. On this stage, Miners perform the // Ending Algorithm and other operations. ENDING_MINING, // Lottery is completed - this is set after the Mining Stage ends. // In this stage, Lottery Winners can claim their prizes. COMPLETION, // DISABLED stage. Used when we want a lottery contract to be // absolutely disabled - so no state-modifying functions could // be called. // This is used in DelegateCall scenarios, where state-contract // delegate-calls code contract, to save on deployment costs. DISABLED } // Ending algorithm types enum. enum EndingAlgoType { // 1. Mined Winner Selection Algorithm. // This algorithm is executed by a Lottery Miner in a single // transaction, on Mining Step 2. // // On that single transaction, all ending scores for all // holders are computed, and a sorted winner array is formed, // which is written onto the LotteryStorage state. // Thus, it's gas expensive, and suitable only for small // holder numbers (up to 300). // // Pros: // + Guaranteed deterministically specifiable winner prize // distribution - for example, if we specify that there // must be 2 winners, of which first gets 60% of prize funds, // and second gets 40% of prize funds, then it's // guarateed that prize funds will be distributed just // like that. // // + Low gas cost of prize claims - only ~ 40,000 gas for // claiming a prize. // // Cons: // - Not scaleable - as the Winner Selection Algorithm is // executed in a single transaction, it's limited by // block gas limit - 12,500,000 on the MainNet. // Thus, the lottery is limited to ~300 holders, and // max. ~200 winners of those holders. // So, it's suitable for only express-lotteries, where // a lottery runs only until ~300 holders are reached. // // - High mining costs - if lottery has 300 holders, // mining transaction takes up whole block gas limit. // MinedWinnerSelection, // 2. Winner Self-Validation Algorithm. // // This algorithm does no operations during the Mining Stage // (except for setting up a Random Seed in Lottery Storage) - // the winner selection (obtaining a winner rank) is done by // the winners themselves, when calling the prize claim // functions. // // This algorithm relies on a fact that by the time that // random seed is obtained, all data needed for winner selection // is already there - the holder scores of the Active Stage // (ether contributed, time factors, token balance), and // the Random Data (random seed + nonce (holder's address)), // so, there is no need to compute and sort the scores for the // whole holder array. // // It's done like this: the holder checks if he's a winner, using // a view-function off-chain, and if so, he calls the // claimWinnerPrize() function, which obtains his winner rank // on O(n) time, and does no writing to contract states, // except for prize transfer-related operations. // // When computing the winner's rank on LotteryStorage, // O(n) time is needed, as we loop through the holders array, // computing ending scores for each holder, using already-known // data. // However that means that for every prize claim, all scores of // all holders must be re-computed. // Computing a score for a single holder takes roughly 1500 gas // (400 for 3 slots SLOAD, and ~300 for arithmetic operations). // // So, this algorithm makes prize claims more expensive for // every lottery holder. // If there's 1000 holders, prize claim takes up 1,500,000 gas, // so, this algorithm is not suitable for small prizes, // because gas fee would be higher than the prize amount won. // // Pros: // + Guaranteed deterministically specifiable winner prize // distribution (same as for algorithm 1). // // + No mining costs for winner selection algorithm. // // + More scalable than algorithm 1. // // Cons: // - High gas costs of prize claiming, rising with the number // of lottery holders - 1500 for every lottery holder. // Thus, suitable for only large prize amounts. // WinnerSelfValidation, // 3. Rolled-Randomness algorithm. // // This algorithm is the most cheapest in terms of gas, but // the winner prize distribution is non-deterministic. // // This algorithm doesn't employ miners (no mining costs), // and doesn't require to compute scores for every holder // prior to getting a winner's rank, thus is the most scalable. // // It works like this: a holder checks his winner status by // computing only his own randomized score (rolling a random // number from the random seed, and multiplying it by holder's // Active Stage score), and computing this randomized-score's // ratio relative to maximum available randomized score. // The higher the ratio, the higher the winner rank is. // // However, many players can roll very high or low scores, and // get the same prizes, so it's difficult to make a fair and // efficient deterministic prize distribution mechanism, so // we have to fallback to specific heuristic workarounds. // // Pros: // + Scalable: O(1) complexity for computing a winner rank, // so there can be an unlimited amount of lottery holders, // and gas costs for winner selection and prize claim would // still be constant & low. // // + Gas-efficient: gas costs for all winner-related operations // are constant and low, because only single holder's score // is computed. // // + Doesn't require mining - even more gas savings. // // Cons: // + Hard to make a deterministic and fair prize distribution // mechanism, because of un-known environment - as only // single holder's score is compared to max-available // random score, not taking into account other holder // scores. // RolledRandomness } /** * Gas-efficient, minimal config, which specifies only basic, * most-important and most-used settings. */ struct LotteryConfig { // ================ Misc Settings =============== // // --------- Slot --------- // // Initial lottery funds (initial market cap). // Specified by pool, and is used to check if initial funds // transferred to fallback are correct - equal to this value. uint initialFunds; // --------- Slot --------- // // The minimum ETH value of lottery funds, that, once // reached on an exchange liquidity pool (Uniswap, or our // contract), must be guaranteed to not shrink below this value. // // This is accomplished in _transfer() function, by denying // all sells that would drop the ETH amount in liquidity pool // below this value. // // But on initial lottery stage, before this minimum requirement // is reached for the first time, all sells are allowed. // // This value is expressed in ETH - total amount of ETH funds // that we own in Uniswap liquidity pair. // // So, if initial funds were 10 ETH, and this is set to 100 ETH, // after liquidity pool's ETH value reaches 100 ETH, all further // sells which could drop the liquidity amount below 100 ETH, // would be denied by require'ing in _transfer() function // (transactions would be reverted). // uint128 fundRequirement_denySells; // ETH value of our funds that we own in Uniswap Liquidity Pair, // that's needed to start the Finishing Stage. uint128 finishCriteria_minFunds; // --------- Slot --------- // // Maximum lifetime of a lottery - maximum amount of time // allowed for lottery to stay active. // By default, it's two weeks. // If lottery is still active (hasn't returned funds) after this // time, lottery will stop on the next token transfer. uint32 maxLifetime; // Maximum prize claiming time - for how long the winners // may be able to claim their prizes after lottery ending. uint32 prizeClaimTime; // Token transfer burn rates for buyers, and a default rate for // sells and non-buy-sell transfers. uint32 burn_buyerRate; uint32 burn_defaultRate; // Maximum amount of tokens (in percentage of initial supply) // to be allowed to own by a single wallet. uint32 maxAmountForWallet_percentageOfSupply; // The required amount of time that must pass after // the request to Randomness Provider has been made, for // external actors to be able to initiate alternative // seed generation algorithm. uint32 REQUIRED_TIME_WAITING_FOR_RANDOM_SEED; // ================ Profit Shares =============== // // "Mined Uniswap Lottery" ending Ether funds, which were obtained // by removing token liquidity from Uniswap, are transfered to // these recipient categories: // // 1. The Main Pool: Initial funds, plus Pool's profit share. // 2. The Owner: Owner's profit share. // // 3. The Miners: Miner rewards for executing the winner // selection algorithm stages. // The more holders there are, the more stages the // winner selection algorithm must undergo. // Each Miner, who successfully completed an algorithm // stage, will get ETH reward equal to: // (minerProfitShare / totalAlgorithmStages). // // 4. The Lottery Winners: All remaining funds are given to // Lottery Winners, which were determined by executing // the Winner Selection Algorithm at the end of the lottery // (Miners executed it). // The Winners can claim their prizes by calling a // dedicated function in our contract. // // The profit shares of #1 and #2 have controlled value ranges // specified in CoreUniLotterySettings. // // All these shares are expressed as percentages of the // lottery profit amount (totalReturn - initialFunds). // Percentages are expressed using the PERCENT constant, // defined in CoreUniLotterySettings. // // Here we specify profit shares of Pool, Owner, and the Miners. // Winner Prize Fund is all that's left (must be more than 50% // of all profits). // uint32 poolProfitShare; uint32 ownerProfitShare; // --------- Slot --------- // uint32 minerProfitShare; // =========== Lottery Finish criteria =========== // // Lottery finish by design is a whole soft stage, that // starts when criteria for holders and fund gains are met. // During this stage, for every token transfer, a pseudo-random // number will be rolled for lottery finish, with increasing // probability. // // There are 2 ways that this probability increase is // implemented: // 1. Increasing on every new holder. // 2. Increasing on every transaction after finish stage // was initiated. // // On every new holder, probability increases more than on // new transactions. // // However, if during this stage some criteria become // no-longer-met, the finish stage is cancelled. // This cancel can be implemented by setting finish probability // to zero, or leaving it as it was, but pausing the finishing // stage. // This is controlled by finish_resetProbabilityOnStop flag - // if not set, probability stays the same, when the finishing // stage is discontinued. // ETH value of our funds that we own in Uniswap Liquidity Pair, // that's needed to start the Finishing Stage. // // LOOK ABOVE - arranged for tight-packing. // Minimum number of token holders required to start the // finishing stage. uint32 finishCriteria_minNumberOfHolders; // Minimum amount of time that lottery must be active. uint32 finishCriteria_minTimeActive; // Initial finish probability, when finishing stage was // just initiated. uint32 finish_initialProbability; // Finishing probability increase steps, for every new // transaction and every new holder. // If holder number decreases, probability decreases. uint32 finish_probabilityIncreaseStep_transaction; uint32 finish_probabilityIncreaseStep_holder; // =========== Winner selection config =========== // // Winner selection algorithm settings. // // Algorithm is based on score, which is calculated for // every holder on lottery finish, and is comprised of // the following parts. // Each part is normalized to range ( 0 - scorePoints ), // from smallest to largest value of each holder; // // After scores are computed, they are multiplied by // holder count factor (holderCount / holderCountDivisor), // and finally, multiplied by safely-generated random values, // to get end winning scores. // The top scorers win prizes. // // By default setting, max score is 40 points, and it's // comprised of the following parts: // // 1. Ether contributed (when buying from Uniswap or contract). // Gets added when buying, and subtracted when selling. // Default: 10 points. // // 2. Amount of lottery tokens holder has on finish. // Default: 5 points. // // 3. Ether contributed, multiplied by the relative factor // of time - that is/*, "block.timestamp" */minus "lotteryStartTime". // This way, late buyers can get more points even if // they get little tokens and don't spend much ether. // Default: 5 points. // // 4. Refferrer bonus. For every player that joined with // your referral ID, you get (that player's score) / 10 // points! This goes up to specified max score. // Also, every player who provides a valid referral ID, // gets 2 points for free! // Default max bonus: 20 points. // int16 maxPlayerScore_etherContributed; int16 maxPlayerScore_tokenHoldingAmount; int16 maxPlayerScore_timeFactor; int16 maxPlayerScore_refferalBonus; // --------- Slot --------- // // Score-To-Random ration data (as a rational ratio number). // For example if 1:5, then scorePart = 1, and randPart = 5. uint16 randRatio_scorePart; uint16 randRatio_randPart; // Time factor divisor - interval of time, in seconds, after // which time factor is increased by one. uint16 timeFactorDivisor; // Bonus score a player should get when registering a valid // referral code obtained from a referrer. int16 playerScore_referralRegisteringBonus; // Are we resetting finish probability when finishing stage // stops, if some criteria are no longer met? bool finish_resetProbabilityOnStop; // =========== Winner Prize Fund Settings =========== // // There are 2 available modes that we can use to distribute // winnings: a computable sequence (geometrical progression), // or an array of winner prize fund share percentages. // More gas efficient is to use a computable sequence, // where each winner gets a share equal to (factor * fundsLeft). // Factor is in range [0.01 - 1.00] - simulated as [1% - 100%]. // // For example: // Winner prize fund is 100 ethers, Factor is 1/4 (25%), and // there are 5 winners total (winnerCount), and sequenced winner // count is 2 (sequencedWinnerCount). // // So, we pre-compute the upper shares, till we arrive to the // sequenced winner count, in a loop: // - Winner 1: 0.25 * 100 = 25 eth; 100 - 25 = 75 eth left. // - Winner 2: 0.25 * 75 ~= 19 eth; 75 - 19 = 56 eth left. // // Now, we compute the left-over winner shares, which are // winners that get their prizes from the funds left after the // sequence winners. // // So, we just divide the leftover funds (56 eth), by 3, // because winnerCount - sequencedWinnerCount = 3. // - Winner 3 = 56 / 3 = 18 eth; // - Winner 4 = 56 / 3 = 18 eth; // - Winner 5 = 56 / 3 = 18 eth; // // If this value is 0, then we'll assume that array-mode is // to be used. uint32 prizeSequenceFactor; // Maximum number of winners that the prize sequence can yield, // plus the leftover winners, which will get equal shares of // the remainder from the first-prize sequence. uint16 prizeSequence_winnerCount; // How many winners would get sequence-computed prizes. // The left-over winners // This is needed because prizes in sequence tend to zero, so // we need to limit the sequence to avoid very small prizes, // and to avoid the remainder. uint16 prizeSequence_sequencedWinnerCount; // Initial token supply (without decimals). uint48 initialTokenSupply; // Ending Algorithm type. // More about the 3 algorithm types above. uint8 endingAlgoType; // --------- Slot --------- // // Array mode: The winner profit share percentages array. // For example, lottery profits can be distributed this way: // // Winner profit shares (8 winners): // [ 20%, 15%, 10%, 5%, 4%, 3%, 2%, 1% ] = 60% of profits. // Owner profits: 10% // Pool profits: 30% // // Pool profit share is not defined explicitly in the config, so // when we internally validate specified profit shares, we // assume the pool share to be the left amount until 100% , // but we also make sure that this amount is at least equal to // MIN_POOL_PROFITS, defined in CoreSettings. // uint32[] winnerProfitShares; } // ========================= Constants ========================= // // The Miner Profits - max/min values. // These aren't defined in Core Settings, because Miner Profits // are only specific to this lottery type. uint32 constant MIN_MINER_PROFITS = 1 * PERCENT; uint32 constant MAX_MINER_PROFITS = 10 * PERCENT; // Uniswap Router V2 contract instance. // Address is the same for MainNet, and all public testnets. IUniswapRouter constant uniswapRouter = IUniswapRouter( address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ) ); // Public-accessible ERC20 token specific constants. string constant public name = "UniLottery Token"; string constant public symbol = "ULT"; uint256 constant public decimals = 18; // =================== State Variables =================== // // ------- Initial Slots ------- // // The config which is passed to constructor. LotteryConfig internal cfg; // ------- Slot ------- // // The Lottery Storage contract, which stores all holder data, // such as scores, referral tree data, etc. LotteryStorage public lotStorage; // ------- Slot ------- // // Pool address. Set on constructor from msg.sender. address payable public poolAddress; // ------- Slot ------- // // Randomness Provider address. address public randomnessProvider; // ------- Slot ------- // // Exchange address. In Uniswap mode, it's the Uniswap liquidity // pair's address, where trades execute. address public exchangeAddress; // Start date. uint32 public startDate; // Completion (Mining Phase End) date. uint32 public completionDate; // The date when Randomness Provider was called, requesting a // random seed for the lottery finish. // Also, when this variable becomes Non-Zero, it indicates that we're // on Ending Stage Part One: waiting for the random seed. uint32 finish_timeRandomSeedRequested; // ------- Slot ------- // // WETH address. Set by calling Router's getter, on constructor. address WETHaddress; // Is the WETH first or second token in our Uniswap Pair? bool uniswap_ethFirst; // If we are, or were before, on finishing stage, this is the // probability of lottery going to Ending Stage on this transaction. uint32 finishProbablity; // Re-Entrancy Lock (Mutex). // We protect for reentrancy in the Fund Transfer functions. bool reEntrancyMutexLocked; // On which stage we are currently. uint8 public lotteryStage; // Indicator for whether the lottery fund gains have passed a // minimum fund gain requirement. // After that time point (when this bool is set), the token sells // which could drop the fund value below the requirement, would // be denied. bool fundGainRequirementReached; // The current step of the Mining Stage. uint16 miningStep; // If we're currently on Special Transfer Mode - that is, we allow // direct transfers between parties even in NON-ACTIVE state. bool specialTransferModeEnabled; // ------- Slot ------- // // Per-Transaction Pseudo-Random hash value (transferHashValue). // This value is computed on every token transfer, by keccak'ing // the last (current) transferHashValue, msg.sender, block.timestamp, and // transaction count. // // This is used on Finishing Stage, as a pseudo-random number, // which is used to check if we should end the lottery (move to // Ending Stage). uint256 transferHashValue; // ------- Slot ------- // // On lottery end, get & store the lottery total ETH return // (including initial funds), and profit amount. uint128 public ending_totalReturn; uint128 public ending_profitAmount; // ------- Slot ------- // // The mapping that contains TRUE for addresses that already claimed // their lottery winner prizes. // Used only in COMPLETION, on claimWinnerPrize(), to check if // msg.sender has already claimed his prize. mapping( address => bool ) public prizeClaimersAddresses; // ============= Private/internal functions ============= // // Pool Only modifier. modifier poolOnly { require( msg.sender == poolAddress/*, "Function can be called only by the pool!" */); _; } // Only randomness provider allowed modifier. modifier randomnessProviderOnly { require( msg.sender == randomnessProvider/*, "Function can be called only by the UniLottery" " Randomness Provider!" */); _; } // Execute function only on specific lottery stage. modifier onlyOnStage( STAGE _stage ) { require( lotteryStage == uint8( _stage )/*, "Function cannot be called on current stage!" */); _; } // Modifier for protecting the function from re-entrant calls, // by using a locked Re-Entrancy Lock (Mutex). modifier mutexLOCKED { require( ! reEntrancyMutexLocked/*, "Re-Entrant Calls are NOT ALLOWED!" */); reEntrancyMutexLocked = true; _; reEntrancyMutexLocked = false; } // Check if we're currently on a specific stage. function onStage( STAGE _stage ) internal view returns( bool ) { return ( lotteryStage == uint8( _stage ) ); } /** * Check if token transfer to specific wallet won't exceed * maximum token amount allowed to own by a single wallet. * * @return true, if holder's balance with "amount" added, * would exceed the max allowed single holder's balance * (by default, that is 5% of total supply). */ function transferExceedsMaxBalance( address holder, uint amount ) internal view returns( bool ) { uint maxAllowedBalance = ( totalSupply() * cfg.maxAmountForWallet_percentageOfSupply ) / ( _100PERCENT ); return ( ( balanceOf( holder ) + amount ) > maxAllowedBalance ); } /** * Update holder data. * This function is called by _transfer() function, just before * transfering final amount of tokens directly from sender to * receiver. * At this point, all burns/mints have been done, and we're sure * that this transfer is valid and must be successful. * * In all modes, this function is used to update the holder array. * * However, on external exchange modes (e.g. on Uniswap mode), * it is also used to track buy/sell ether value, to update holder * scores, when token buys/sells cannot be tracked directly. * * If, however, we use Standalone mode, we are the exchange, * so on _transfer() we already know the ether value, which is * set to currentBuySellEtherValue variable. * * @param amountSent - the token amount that is deducted from * sender's balance. This includes burn, and owner fee. * * @param amountReceived - the token amount that receiver * actually receives, after burns and fees. * * @return holderCountChanged - indicates whether holder count * changes during this transfer - new holder joins or leaves * (true), or no change occurs (false). */ function updateHolderData_preTransfer( address sender, address receiver, uint256 amountSent, uint256 amountReceived ) internal returns( bool holderCountChanged ) { // Update holder array, if new token holder joined, or if // a holder transfered his whole balance. holderCountChanged = false; // Sender transferred his whole balance - no longer a holder. if( balanceOf( sender ) == amountSent ) { lotStorage.removeHolder( sender ); holderCountChanged = true; } // Receiver didn't have any tokens before - add it to holders. if( balanceOf( receiver ) == 0 && amountReceived > 0 ) { lotStorage.addHolder( receiver ); holderCountChanged = true; } // Update holder score factors: if buy/sell occured, update // etherContributed and timeFactors scores, // and also propagate the scores through the referral chain // to the parent referrers (this is done in Storage contract). // This lottery operates only on external exchange (Uniswap) // mode, so we have to find out the buy/sell Ether value by // calling the external exchange (Uniswap pair) contract. // Temporary variable to store current transfer's buy/sell // value in Ethers. int buySellValue; // Sender is an exchange - buy detected. if( sender == exchangeAddress && receiver != exchangeAddress ) { // Use the Router's functionality. // Set the exchange path to WETH -> ULT // (ULT is Lottery Token, and it's address is our address). address[] memory path = new address[]( 2 ); path[ 0 ] = WETHaddress; path[ 1 ] = address(this); uint[] memory ethAmountIn = uniswapRouter.getAmountsIn( amountSent, // uint amountOut, path // address[] path ); buySellValue = int( ethAmountIn[ 0 ] ); // Compute time factor value for the current ether value. // buySellValue is POSITIVE. // When computing Time Factors, leave only 2 ether decimals. int timeFactorValue = ( buySellValue / (1 ether / 100) ) * int( (block.timestamp - startDate) / cfg.timeFactorDivisor ); if( timeFactorValue == 0 ) timeFactorValue = 1; // Update and propagate the buyer (receiver) scores. lotStorage.updateAndPropagateScoreChanges( receiver, int80( buySellValue ), int80( timeFactorValue ), int80( amountReceived ) ); } // Receiver is an exchange - sell detected. else if( sender != exchangeAddress && receiver == exchangeAddress ) { // Use the Router's functionality. // Set the exchange path to ULT -> WETH // (ULT is Lottery Token, and it's address is our address). address[] memory path = new address[]( 2 ); path[ 0 ] = address(this); path[ 1 ] = WETHaddress; uint[] memory ethAmountOut = uniswapRouter.getAmountsOut( amountReceived, // uint amountIn path // address[] path ); // It's a sell (ULT -> WETH), so set value to NEGATIVE. buySellValue = int( -1 ) * int( ethAmountOut[ 1 ] ); // Compute time factor value for the current ether value. // buySellValue is NEGATIVE. int timeFactorValue = ( buySellValue / (1 ether / 100) ) * int( (block.timestamp - startDate) / cfg.timeFactorDivisor ); if( timeFactorValue == 0 ) timeFactorValue = -1; // Update and propagate the seller (sender) scores. lotStorage.updateAndPropagateScoreChanges( sender, int80( buySellValue ), int80( timeFactorValue ), -1 * int80( amountSent ) ); } // Neither Sender nor Receiver are exchanges - default transfer. // Tokens just got transfered between wallets, without // exchanging for ETH - so etherContributed_change = 0. // On this case, update both sender's & receiver's scores. // else { buySellValue = 0; lotStorage.updateAndPropagateScoreChanges( sender, 0, 0, -1 * int80( amountSent ) ); lotStorage.updateAndPropagateScoreChanges( receiver, 0, 0, int80( amountReceived ) ); } // Check if lottery liquidity pool funds have already // reached a minimum required ETH value. uint ethFunds = getCurrentEthFunds(); if( !fundGainRequirementReached && ethFunds >= cfg.fundRequirement_denySells ) { fundGainRequirementReached = true; } // Check whether this token transfer is allowed if it's a sell // (if buySellValue is negative): // // If we've already reached the minimum fund gain requirement, // and this sell would shrink lottery liquidity pool's ETH funds // below this requirement, then deny this sell, causing this // transaction to fail. if( fundGainRequirementReached && buySellValue < 0 && ( uint( -1 * buySellValue ) >= ethFunds || ethFunds - uint( -1 * buySellValue ) < cfg.fundRequirement_denySells ) ) { require( false/*, "This sell would drop the lottery ETH funds" "below the minimum requirement threshold!" */); } } /** * Check for finishing stage start conditions. * - If some conditions are met, start finishing stage! * Do it by setting "onFinishingStage" bool. * - If we're currently on finishing stage, and some condition * is no longer met, then stop the finishing stage. */ function checkFinishingStageConditions() internal { // Firstly, check if lottery hasn't exceeded it's maximum lifetime. // If so, don't check anymore, just set finishing stage, and // end the lottery on further call of checkForEnding(). if( (block.timestamp - startDate) > cfg.maxLifetime ) { lotteryStage = uint8( STAGE.FINISHING ); return; } // Compute & check the finishing criteria. // Notice that we adjust the config-specified fund gain // percentage increase to uint-mode, by adding 100 percents, // because we don't deal with negative percentages, and here // we represent loss as a percentage below 100%, and gains // as percentage above 100%. // So, if in regular gains notation, it's said 10% gain, // in uint mode, it's said 110% relative increase. // // (Also, remember that losses are impossible in our lottery // working scheme). if( lotStorage.getHolderCount() >= cfg.finishCriteria_minNumberOfHolders && getCurrentEthFunds() >= cfg.finishCriteria_minFunds && (block.timestamp - startDate) >= cfg.finishCriteria_minTimeActive ) { if( onStage( STAGE.ACTIVE ) ) { // All conditions are met - start the finishing stage. lotteryStage = uint8( STAGE.FINISHING ); emit FinishingStageStarted(); } } else if( onStage( STAGE.FINISHING ) ) { // However, what if some condition was not met, but we're // already on the finishing stage? // If so, we must stop the finishing stage. // But what to do with the finishing probability? // Config specifies if it should be reset or maintain it's // value until the next time finishing stage is started. lotteryStage = uint8( STAGE.ACTIVE ); if( cfg.finish_resetProbabilityOnStop ) finishProbablity = cfg.finish_initialProbability; emit FinishingStageStopped(); } } /** * We're currently on finishing stage - so let's check if * we should end the lottery block.timestamp! * * This function is called from _transfer(), only if we're sure * that we're currently on finishing stage (onFinishingStage * variable is set). * * Here, we compute the pseudo-random number from hash of * current message's sender, block.timestamp, and other values, * and modulo it to the current finish probability. * If it's equal to 1, then we end the lottery! * * Also, here we update the finish probability according to * probability update criteria - holder count, and tx count. * * @param holderCountChanged - indicates whether Holder Count * has changed during this transfer (new holder joined, or * a holder sold all his tokens). */ function checkForEnding( bool holderCountChanged ) internal { // At first, check if lottery max lifetime is exceeded. // If so, start ending procedures right block.timestamp. if( (block.timestamp - startDate) > cfg.maxLifetime ) { startEndingStage(); return; } // Now, we know that lottery lifetime is still OK, and we're // currently on Finishing Stage (because this function is // called only when onFinishingStage is set). // // Now, check if we should End the lottery, by computing // a modulo on a pseudo-random number, which is a transfer // hash, computed for every transfer on _transfer() function. // // Get the modulo amount according to current finish // probability. // We use precision of 0.01% - notice the "10000 *" before // 100 PERCENT. // Later, when modulo'ing, we'll check if value is below 10000. // uint prec = 10000; uint modAmount = (prec * _100PERCENT) / finishProbablity; if( ( transferHashValue % modAmount ) <= prec ) { // Finish probability is met! Commence lottery end - // start Ending Stage. startEndingStage(); return; } // Finish probability wasn't met. // Update the finish probability, by increasing it! // Transaction count criteria. // As we know that this function is called on every new // transfer (transaction), we don't check if transactionCount // increased or not - we just perform probability update. finishProbablity += cfg.finish_probabilityIncreaseStep_transaction; // Now, perform holder count criteria update. // Finish probability increases, no matter if holder count // increases or decreases. if( holderCountChanged ) finishProbablity += cfg.finish_probabilityIncreaseStep_holder; } /** * Start the Ending Stage, by De-Activating the lottery, * to deny all further token transfers (excluding the one when * removing liquidity from Uniswap), and transition into the * Mining Phase - set the lotteryStage to MINING. */ function startEndingStage() internal { lotteryStage = uint8( STAGE.ENDING_MINING ); } /** * Execute the first step of the Mining Stage - request a * Random Seed from the Randomness Provider. * * Here, we call the Randomness Provider, asking for a true random seed * to be passed to us into our callback, named * "finish_randomnessProviderCallback()". * * When that callback will be called, our storage's random seed will * be set, and we'll be able to start the Ending Algorithm on * further mining steps. * * Notice that Randomness Provider must already be funded, to * have enough Ether for Provable fee and the gas costs of our * callback function, which are quite high, because of winner * selection algorithm, which is computationally expensive. * * The Randomness Provider is always funded by the Pool, * right before the Pool deploys and starts a new lottery, so * as every lottery calls the Randomness Provider only once, * the one-call-fund method for every lottery is sufficient. * * Also notice, that Randomness Provider might fail to call * our callback due to some unknown reasons! * Then, the lottery profits could stay locked in this * lottery contract forever ?!! * * No! We've thought about that - we've implemented the * Alternative Ending mechanism, where, if specific time passes * after we've made a request to Randomness Provider, and * callback hasn't been called yet, we allow external actor to * execute the Alternative ending, which basically does the * same things as the default ending, just that the Random Seed * will be computed locally in our contract, using the * Pseudo-Random mechanism, which could compute a reasonably * fair and safe value using data from holder array, and other * values, described in more detail on corresponding function's * description. */ function mine_requestRandomSeed() internal { // We're sure that the Randomness Provider has enough funds. // Execute the random request, and get ready for Ending Algorithm. IRandomnessProvider( randomnessProvider ) .requestRandomSeedForLotteryFinish(); // Store the time when random seed has been requested, to // be able to alternatively handle the lottery finish, if // randomness provider doesn't call our callback for some // reason. finish_timeRandomSeedRequested = uint32( block.timestamp ); // Emit appropriate events. emit RandomnessProviderCalled(); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Transfer the Owner & Pool profit shares, when lottery ends. * This function is the first one that's executed on the Mining * Stage. * This is the first step of Mining. So, the Miner who executes this * function gets the mining reward. * * This function's job is to Gather the Profits & Initial Funds, * and Transfer them to Profiters - that is, to The Pool, and * to The Owner. * * The Miners' profit share and Winner Prize Fund stay in this * contract. * * On this function, we (in this order): * * 1. Remove all liquidity from Uniswap (if using Uniswap Mode), * pulling it to our contract's wallet. * * 2. Transfer the Owner and the Pool ETH profit shares to * Owner and Pool addresses. * * * This function transfers Ether out of our contract: * - We transfer the Profits to Pool and Owner addresses. */ function mine_removeUniswapLiquidityAndTransferProfits() internal mutexLOCKED { // We've already approved our token allowance to Router. // Now, approve Uniswap liquidity token's Router allowance. ERC20( exchangeAddress ).approve( address(uniswapRouter), uint(-1) ); // Enable the SPECIAL-TRANSFER mode, to allow Uniswap to transfer // the tokens from Pair to Router, and then from Router to us. specialTransferModeEnabled = true; // Remove liquidity! uint amountETH = uniswapRouter .removeLiquidityETHSupportingFeeOnTransferTokens( address(this), // address token, ERC20( exchangeAddress ).balanceOf( address(this) ), 0, // uint amountTokenMin, 0, // uint amountETHMin, address(this), // address to, (block.timestamp + 10000000) // uint deadline ); // Tokens are transfered. Disable the special transfer mode. specialTransferModeEnabled = false; // Check that we've got a correct amount of ETH. require( address(this).balance >= amountETH && address(this).balance >= cfg.initialFunds/*, "Incorrect amount of ETH received from Uniswap!" */); // Compute the Profit Amount (current balance - initial funds). ending_totalReturn = uint128( address(this).balance ); ending_profitAmount = ending_totalReturn - uint128( cfg.initialFunds ); // Compute, and Transfer Owner's profit share and // Pool's profit share to their respective addresses. uint poolShare = ( ending_profitAmount * cfg.poolProfitShare ) / ( _100PERCENT ); uint ownerShare = ( ending_profitAmount * cfg.ownerProfitShare ) / ( _100PERCENT ); // To pool, transfer it's profit share plus initial funds. IUniLotteryPool( poolAddress ).lotteryFinish { value: poolShare + cfg.initialFunds } ( ending_totalReturn, ending_profitAmount ); // Transfer Owner's profit share. OWNER_ADDRESS.transfer( ownerShare ); // Emit ending event. emit LotteryEnd( ending_totalReturn, ending_profitAmount ); } /** * Executes a single step of the Winner Selection Algorithm * (the Ending Algorithm). * The algorithm itself is being executed in the Storage contract. * * On current design, whole algorithm is executed in a single step. * * This function is executed only in the Mining stage, and * accounts for most of the gas spent during mining. */ function mine_executeEndingAlgorithmStep() internal { // Launch the winner algorithm, to execute the next step. lotStorage.executeWinnerSelectionAlgorithm(); } // =============== Public functions =============== // /** * Constructor of this delegate code contract. * Here, we set OUR STORAGE's lotteryStage to DISABLED, because * we don't want anybody to call this contract directly. */ constructor() { lotteryStage = uint8( STAGE.DISABLED ); } /** * Construct the lottery contract which is delegating it's * call to us. * * @param config - LotteryConfig structure to use in this lottery. * * Future approach: ABI-encoded Lottery Config * (different implementations might use different config * structures, which are ABI-decoded inside the implementation). * * Also, this "config" includes the ABI-encoded temporary values, * which are not part of persisted LotteryConfig, but should * be used only in constructor - for example, values to be * assigned to storage variables, such as ERC20 token's * name, symbol, and decimals. * * @param _poolAddress - Address of the Main UniLottery Pool, which * provides initial funds, and receives it's profit share. * * @param _randomProviderAddress - Address of a Randomness Provider, * to use for obtaining random seeds. * * @param _storageAddress - Address of a Lottery Storage. * Storage contract is a separate contract which holds all * lottery token holder data, such as intermediate scores. * */ function construct( LotteryConfig memory config, address payable _poolAddress, address _randomProviderAddress, address _storageAddress ) external { // Check if contract wasn't already constructed! require( poolAddress == address( 0 )/*, "Contract is already constructed!" */); // Set the Pool's Address - notice that it's not the // msg.sender, because lotteries aren't created directly // by the Pool, but by the Lottery Factory! poolAddress = _poolAddress; // Set the Randomness Provider address. randomnessProvider = _randomProviderAddress; // Check the minimum & maximum requirements for config // profit & lifetime parameters. require( config.maxLifetime <= MAX_LOTTERY_LIFETIME/*, "Lottery maximum lifetime is too high!" */); require( config.poolProfitShare >= MIN_POOL_PROFITS && config.poolProfitShare <= MAX_POOL_PROFITS/*, "Pool profit share is invalid!" */); require( config.ownerProfitShare >= MIN_OWNER_PROFITS && config.ownerProfitShare <= MAX_OWNER_PROFITS/*, "Owner profit share is invalid!" */); require( config.minerProfitShare >= MIN_MINER_PROFITS && config.minerProfitShare <= MAX_MINER_PROFITS/*, "Miner profit share is invalid!" */); // Check if time factor divisor is higher than 2 minutes. // That's because int40 wouldn't be able to handle precisions // of smaller time factor divisors. require( config.timeFactorDivisor >= 2 minutes /*, "Time factor divisor is lower than 2 minutes!"*/ ); // Check if winner profit share is good. uint32 totalWinnerShare = (_100PERCENT) - config.poolProfitShare - config.ownerProfitShare - config.minerProfitShare; require( totalWinnerShare >= MIN_WINNER_PROFIT_SHARE/*, "Winner profit share is too low!" */); // Check if ending algorithm params are good. require( config.randRatio_scorePart != 0 && config.randRatio_randPart != 0 && ( config.randRatio_scorePart + config.randRatio_randPart ) < 10000/*, "Random Ratio params are invalid!" */); require( config.endingAlgoType == uint8( EndingAlgoType.MinedWinnerSelection ) || config.endingAlgoType == uint8( EndingAlgoType.WinnerSelfValidation ) || config.endingAlgoType == uint8( EndingAlgoType.RolledRandomness )/*, "Wrong Ending Algorithm Type!" */); // Set the number of winners (winner count). // If using Computed Sequence winner prize shares, set that // value, and if it's zero, then we're using the Array-Mode // prize share specification. if( config.prizeSequence_winnerCount == 0 && config.winnerProfitShares.length != 0 ) config.prizeSequence_winnerCount = uint16( config.winnerProfitShares.length ); // Setup our Lottery Storage - initialize, and set the // Algorithm Config. LotteryStorage _lotStorage = LotteryStorage( _storageAddress ); // Setup a Winner Score Config for the winner selection algo, // to be used in the Lottery Storage. LotteryStorage.WinnerAlgorithmConfig memory winnerConfig; // Algorithm type. winnerConfig.endingAlgoType = config.endingAlgoType; // Individual player max score parts. winnerConfig.maxPlayerScore_etherContributed = config.maxPlayerScore_etherContributed; winnerConfig.maxPlayerScore_tokenHoldingAmount = config.maxPlayerScore_tokenHoldingAmount; winnerConfig.maxPlayerScore_timeFactor = config.maxPlayerScore_timeFactor; winnerConfig.maxPlayerScore_refferalBonus = config.maxPlayerScore_refferalBonus; // Score-To-Random ratio parts. winnerConfig.randRatio_scorePart = config.randRatio_scorePart; winnerConfig.randRatio_randPart = config.randRatio_randPart; // Set winner count (no.of winners). winnerConfig.winnerCount = config.prizeSequence_winnerCount; // Initialize the storage (bind it to our contract). _lotStorage.initialize( winnerConfig ); // Set our immutable variable. lotStorage = _lotStorage; // Now, set our config to the passed config. cfg = config; // Might be un-needed (can be replaced by Constant on the MainNet): WETHaddress = uniswapRouter.WETH(); } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<< * * Fallback Receive Ether function. * Used to receive ETH funds back from Uniswap, on lottery's end, * when removing liquidity. */ receive() external payable { emit FallbackEtherReceiver( msg.sender, msg.value ); } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<< * PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Initialization function. * Here, the most important startup operations are made - * such as minting initial token supply and transfering it to * the Uniswap liquidity pair, in exchange for UNI-v2 tokens. * * This function is called by the pool, when transfering * initial funds to this contract. * * What's payable? * - Pool transfers initial funds to our contract. * - We transfer that initial fund Ether to Uniswap liquidity pair * when creating/providing it. */ function initialize() external payable poolOnly mutexLOCKED onlyOnStage( STAGE.INITIAL ) { // Check if pool transfered correct amount of funds. require( address( this ).balance == cfg.initialFunds/*, "Invalid amount of funds transfered!" */); // Set start date. startDate = uint32( block.timestamp ); // Set the initial transfer hash value. transferHashValue = uint( keccak256( abi.encodePacked( msg.sender, block.timestamp ) ) ); // Set initial finish probability, to be used when finishing // stage starts. finishProbablity = cfg.finish_initialProbability; // ===== Active operations - mint & distribute! ===== // // Mint full initial supply of tokens to our contract address! _mint( address(this), uint( cfg.initialTokenSupply ) * (10 ** decimals) ); // Now - prepare to create a new Uniswap Liquidity Pair, // with whole our total token supply and initial funds ETH // as the two liquidity reserves. // Approve Uniswap Router to allow it to spend our tokens. // Set maximum amount available. _approve( address(this), address( uniswapRouter ), uint(-1) ); // Provide liquidity - the Router will automatically // create a new Pair. uniswapRouter.addLiquidityETH { value: address(this).balance } ( address(this), // address token, totalSupply(), // uint amountTokenDesired, totalSupply(), // uint amountTokenMin, address(this).balance, // uint amountETHMin, address(this), // address to, (block.timestamp + 1000) // uint deadline ); // Get the Pair address - that will be the exchange address. exchangeAddress = IUniswapFactory( uniswapRouter.factory() ) .getPair( WETHaddress, address(this) ); // We assume that the token reserves of the pair are good, // and that we own the full amount of liquidity tokens. // Find out which of the pair tokens is WETH - is it the // first or second one. Use it later, when getting our share. if( IUniswapPair( exchangeAddress ).token0() == WETHaddress ) uniswap_ethFirst = true; else uniswap_ethFirst = false; // Move to ACTIVE lottery stage. // Now, all token transfers will be allowed. lotteryStage = uint8( STAGE.ACTIVE ); // Lottery is initialized. We're ready to emit event. emit LotteryInitialized(); } // Return this lottery's initial funds, as were specified in the config. // function getInitialFunds() external view returns( uint ) { return cfg.initialFunds; } // Return active (still not returned to pool) initial fund value. // If no-longer-active, return 0 (default) - because funds were // already returned back to the pool. // function getActiveInitialFunds() external view returns( uint ) { if( onStage( STAGE.ACTIVE ) ) return cfg.initialFunds; return 0; } /** * Get current Exchange's Token and ETH reserves. * We're on Uniswap mode, so get reserves from Uniswap. */ function getReserves() external view returns( uint _ethReserve, uint _tokenReserve ) { // Use data from Uniswap pair contract. ( uint112 res0, uint112 res1, ) = IUniswapPair( exchangeAddress ).getReserves(); if( uniswap_ethFirst ) return ( res0, res1 ); else return ( res1, res0 ); } /** * Get our share (ETH amount) of the Uniswap Pair ETH reserve, * of our Lottery tokens ULT-WETH liquidity pair. */ function getCurrentEthFunds() public view returns( uint ethAmount ) { IUniswapPair pair = IUniswapPair( exchangeAddress ); ( uint112 res0, uint112 res1, ) = pair.getReserves(); uint resEth = uint( uniswap_ethFirst ? res0 : res1 ); // Compute our amount of the ETH reserve, based on our // percentage of our liquidity token balance to total supply. uint liqTokenPercentage = ( pair.balanceOf( address(this) ) * (_100PERCENT) ) / ( pair.totalSupply() ); // Compute and return the ETH reserve. return ( resEth * liqTokenPercentage ) / (_100PERCENT); } /** * Get current finish probability. * If it's ACTIVE stage, return 0 automatically. */ function getFinishProbability() external view returns( uint32 ) { if( onStage( STAGE.FINISHING ) ) return finishProbablity; return 0; } /** * Generate a referral ID for msg.sender, who must be a token holder. * Referral ID is used to refer other wallets into playing our * lottery. * - Referrer gets bonus points for every wallet that bought * lottery tokens and specified his referral ID. * - Referrees (wallets who got referred by registering a valid * referral ID, corresponding to some referrer), get some * bonus points for specifying (registering) a referral ID. * * Referral ID is a uint256 number, which is generated by * keccak256'ing the holder's address, holder's current * token ballance, and current time. */ function generateReferralID() external onlyOnStage( STAGE.ACTIVE ) { uint256 refID = lotStorage.generateReferralID( msg.sender ); // Emit approppriate events. emit ReferralIDGenerated( msg.sender, refID ); } /** * Register a referral for a msg.sender (must be token holder), * using a valid referral ID got from a referrer. * This function is called by a referree, who obtained a * valid referral ID from some referrer, who previously * generated it using generateReferralID(). * * You can only register a referral once! * When you do so, you get bonus referral points! */ function registerReferral( uint256 referralID ) external onlyOnStage( STAGE.ACTIVE ) { address referrer = lotStorage.registerReferral( msg.sender, cfg.playerScore_referralRegisteringBonus, referralID ); // Emit approppriate events. emit ReferralRegistered( msg.sender, referrer, referralID ); } /** * The most important function of this contract - Transfer Function. * * Here, all token burning, intermediate score tracking, and * finish condition checking is performed, according to the * properties specified in config. */ function _transfer( address sender, address receiver, uint256 amount ) internal override { // Check if transfers are allowed in current state. // On Non-Active stage, transfers are allowed only from/to // our contract. // As we don't have Standalone Mode on this lottery variation, // that means that tokens to/from our contract are travelling // only when we transfer them to Uniswap Pair, and when // Uniswap transfers them back to us, on liquidity remove. // // On this state, we also don't perform any burns nor // holding trackings - just transfer and return. if( !onStage( STAGE.ACTIVE ) && !onStage( STAGE.FINISHING ) && ( sender == address(this) || receiver == address(this) || specialTransferModeEnabled ) ) { super._transfer( sender, receiver, amount ); return; } // Now, we know that we're NOT on special mode. // Perform standard checks & brecks. require( ( onStage( STAGE.ACTIVE ) || onStage( STAGE.FINISHING ) )/*, "Token transfers are only allowed on ACTIVE stage!" */); // Can't transfer zero tokens, or use address(0) as sender. require( amount != 0 && sender != address(0)/*, "Amount is zero, or transfering from zero address." */); // Compute the Burn Amount - if buying tokens from an exchange, // we use a lower burn rate - to incentivize buying! // Otherwise (if selling or just transfering between wallets), // we use a higher burn rate. uint burnAmount; // It's a buy - sender is an exchange. if( sender == exchangeAddress ) burnAmount = ( amount * cfg.burn_buyerRate ) / (_100PERCENT); else burnAmount = ( amount * cfg.burn_defaultRate ) / (_100PERCENT); // Now, compute the final amount to be gotten by the receiver. uint finalAmount = amount - burnAmount; // Check if receiver's balance won't exceed the max-allowed! // Receiver must not be an exchange. if( receiver != exchangeAddress ) { require( !transferExceedsMaxBalance( receiver, finalAmount )/*, "Receiver's balance would exceed maximum after transfer!"*/); } // Now, update holder data array accordingly. bool holderCountChanged = updateHolderData_preTransfer( sender, receiver, amount, // Amount Sent (Pre-Fees) finalAmount // Amount Received (Post-Fees). ); // All is ok - perform the burn and token transfers block.timestamp. // Burn token amount from sender's balance. super._burn( sender, burnAmount ); // Finally, transfer the final amount from sender to receiver. super._transfer( sender, receiver, finalAmount ); // Compute new Pseudo-Random transfer hash, which must be // computed for every transfer, and is used in the // Finishing Stage as a pseudo-random unique value for // every transfer, by which we determine whether lottery // should end on this transfer. // // Compute it like this: keccak the last (current) // transferHashValue, msg.sender, sender, receiver, amount. transferHashValue = uint( keccak256( abi.encodePacked( transferHashValue, msg.sender, sender, receiver, amount ) ) ); // Check if we should be starting a finishing stage block.timestamp. checkFinishingStageConditions(); // If we're on finishing stage, check for ending conditions. // If ending check is satisfied, the checkForEnding() function // starts ending operations. if( onStage( STAGE.FINISHING ) ) checkForEnding( holderCountChanged ); } /** * Callback function, which is called from Randomness Provider, * after it obtains a random seed to be passed to us, after * we have initiated The Ending Stage, on which random seed * is used to generate random factors for Winner Selection * algorithm. */ function finish_randomnessProviderCallback( uint256 randomSeed, uint256 /*callID*/ ) external randomnessProviderOnly { // Set the random seed in the Storage Contract. lotStorage.setRandomSeed( randomSeed ); // If algo-type is not Mined Winner Selection, then by block.timestamp // we assume lottery as COMPL3T3D. if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) ) { lotteryStage = uint8( STAGE.COMPLETION ); completionDate = uint32( block.timestamp ); } } /** * Function checks if we can initiate Alternative Seed generation. * * Alternative approach to Lottery Random Seed is used only when * Randomness Provider doesn't work, and doesn't call the * above callback. * * This alternative approach can be initiated by Miners, when * these conditions are met: * - Lottery is on Ending (Mining) stage. * - Request to Randomness Provider was made at least X time ago, * and our callback hasn't been called yet. * * If these conditions are met, we can initiate the Alternative * Random Seed generation, which generates a seed based on our * state. */ function alternativeSeedGenerationPossible() internal view returns( bool ) { return ( onStage( STAGE.ENDING_MINING ) && ( (block.timestamp - finish_timeRandomSeedRequested) > cfg.REQUIRED_TIME_WAITING_FOR_RANDOM_SEED ) ); } /** * Return this lottery's config, using ABIEncoderV2. */ /*function getLotteryConfig() external view returns( LotteryConfig memory ourConfig ) { return cfg; }*/ /** * Checks if Mining is currently available. */ function isMiningAvailable() external view returns( bool ) { return onStage( STAGE.ENDING_MINING ) && ( miningStep == 0 || ( miningStep == 1 && ( lotStorage.getRandomSeed() != 0 || alternativeSeedGenerationPossible() ) ) ); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Mining function, to be executed on Ending (Mining) stage. * * "Mining" approach is used in this lottery, to use external * actors for executing the gas-expensive Ending Algorithm, * and other ending operations, such as profit transfers. * * "Miners" can be any external actors who call this function. * When Miner successfully completes a Mining Step, he gets * a Mining Reward, which is a certain portion of lottery's profit * share, dedicated to Miners. * * NOT-IMPLEMENTED APPROACH: * * All these operations are divided into "mining steps", which are * smaller components, which fit into reasonable gas limits. * All "steps" are designed to take up similar amount of gas. * * For example, if total lottery profits (total ETH got from * pulling liquidity out of Uniswap, minus initial funds), * is 100 ETH, Miner Profit Share is 10%, and there are 5 mining * steps total, then for a singe step executed, miner will get: * * (100 * 0.1) / 5 = 2 ETH. * * --------------------------------- * * CURRENTLY IMPLEMENTED APPROACH: * * As the above-defined approach would consume very much gas for * inter-step intermediate state storage, we have thought that * for block.timestamp, it's better to have only 2 mining steps, the second of * which performs the whole Winner Selection Algorithm. * * This is because performing the whole algorithm at once would save * us up to 10x more gas in total, than executing it in steps. * * However, this solution is not scalable, because algorithm has * to fit into block gas limit (10,000,000 gas), so we are limited * to a certain safe maximum number of token holders, which is * empirically determined during testing, and defined in the * MAX_SAFE_NUMBER_OF_HOLDERS constant, which is checked against the * config value "finishCriteria_minNumberOfHolders" in constructor. * * So, in this approach, there are only 2 mining steps: * * 1. Remove liquidity from Uniswap, transfer profit shares to * the Pool and the Owner Address, and request Random Seed * from the Randomness Provider. * Reward: 25% of total Mining Rewards. * * 2. Perform the whole Winner Selection Algorithm inside the * Lottery Storage contract. * Reward: 75% of total Mining Rewards. * * * Function transfers Ether out of our contract: * - Transfers the current miner's reward to msg.sender. */ function mine() external onlyOnStage( STAGE.ENDING_MINING ) { uint currentStepReward; // Perform different operations on different mining steps. // Step 0: Remove liquidity from Uniswap, transfer profits to // Pool and Owner addresses. Also, request a Random Seed // from the Randomness Provider. if( miningStep == 0 ) { mine_requestRandomSeed(); mine_removeUniswapLiquidityAndTransferProfits(); // Compute total miner reward amount, then compute this // step's reward later. uint totalMinerRewards = ( ending_profitAmount * cfg.minerProfitShare ) / ( _100PERCENT ); // Step 0 reward is 10% for Algo type 1. if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) ) { currentStepReward = ( totalMinerRewards * (10 * PERCENT) ) / ( _100PERCENT ); } // If other algo-types, second step is not normally needed, // so here we take 80% of miner rewards. // If Randomness Provider won't give us a seed after // specific amount of time, we'll initiate a second step, // with remaining 20% of miner rewords. else { currentStepReward = ( totalMinerRewards * (80 * PERCENT) ) / ( _100PERCENT ); } require( currentStepReward <= totalMinerRewards/*, "BUG 1694" */); } // Step 1: // If we use MinedWinnerSelection algo-type, then execute the // winner selection algorithm. // Otherwise, check if Random Provider hasn't given us a // random seed long enough, so that we have to generate a // seed locally. else { // Check if we can go into this step when using specific // ending algorithm types. if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) ) { require( lotStorage.getRandomSeed() == 0 && alternativeSeedGenerationPossible()/*, "Second Mining Step is not available for " "current Algo-Type on these conditions!" */); } // Compute total miner reward amount, then compute this // step's reward later. uint totalMinerRewards = ( ending_profitAmount * cfg.minerProfitShare ) / ( _100PERCENT ); // Firstly, check if random seed is already obtained. // If not, check if we should generate it locally. if( lotStorage.getRandomSeed() == 0 ) { if( alternativeSeedGenerationPossible() ) { // Set random seed inside the Storage Contract, // but using our contract's transferHashValue as the // random seed. // We believe that this hash has enough randomness // to be considered a fairly good random seed, // because it has beed chain-computed for every // token transfer that has occured in ACTIVE stage. // lotStorage.setRandomSeed( transferHashValue ); // If using Non-Mined algorithm types, reward for this // step is 20% of miner funds. if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) ) { currentStepReward = ( totalMinerRewards * (20 * PERCENT) ) / ( _100PERCENT ); } } else { // If alternative seed generation is not yet possible // (not enough time passed since the rand.provider // request was made), then mining is not available // currently. require( false/*, "Mining not yet available!" */); } } // Now, we know that Random Seed is obtained. // If we use this algo-type, perform the actual // winner selection algorithm. if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) ) { mine_executeEndingAlgorithmStep(); // Set the prize amount to SECOND STEP prize amount (90%). currentStepReward = ( totalMinerRewards * (90 * PERCENT) ) / ( _100PERCENT ); } // Now we've completed both Mining Steps, it means MINING stage // is finally completed! // Transition to COMPLETION stage, and set lottery completion // time to NOW. lotteryStage = uint8( STAGE.COMPLETION ); completionDate = uint32( block.timestamp ); require( currentStepReward <= totalMinerRewards/*, "BUG 2007" */); } // Now, transfer the reward to miner! // Check for bugs too - if the computed amount doesn't exceed. // Increment the mining step - move to next step (if there is one). miningStep++; // Check & Lock the Re-Entrancy Lock for transfers. require( ! reEntrancyMutexLocked/*, "Re-Entrant call detected!" */); reEntrancyMutexLocked = true; // Finally, transfer the reward to message sender! msg.sender.transfer( currentStepReward ); // UnLock ReEntrancy Lock. reEntrancyMutexLocked = false; } /** * Function computes winner prize amount for winner at rank #N. * Prerequisites: Must be called only on STAGE.COMPLETION stage, * because we use the final profits amount here, and that value * (ending_profitAmount) is known only on COMPLETION stage. * * @param rankingPosition - ranking position of a winner. * @return finalPrizeAmount - prize amount, in Wei, of this winner. */ function getWinnerPrizeAmount( uint rankingPosition ) public view returns( uint finalPrizeAmount ) { // Calculate total winner prize fund profit percentage & amount. uint winnerProfitPercentage = (_100PERCENT) - cfg.poolProfitShare - cfg.ownerProfitShare - cfg.minerProfitShare; uint totalPrizeAmount = ( ending_profitAmount * winnerProfitPercentage ) / ( _100PERCENT ); // We compute the prize amounts differently for the algo-type // RolledRandomness, because distribution of these prizes is // non-deterministic - multiple holders could fall onto the // same ranking position, due to randomness of rolled score. // if( cfg.endingAlgoType == uint8(EndingAlgoType.RolledRandomness) ) { // Here, we'll use Prize Sequence Factor approach differently. // We'll use the prizeSequenceFactor value not to compute // a geometric progression, but to compute an arithmetic // progression, where each ranking position will get a // prize equal to // "totalPrizeAmount - rankingPosition * singleWinnerShare" // // singleWinnerShare is computed as a value corresponding // to single-winner's share of total prize amount. // // Using such an approach, winner at rank 0 would get a // prize equal to whole totalPrizeAmount, but, as the // scores are rolled using random factor, it's very unlikely // to get a such high score, so most likely such prize // won't ever be claimed, but it is a possibility. // // Most of the winners in this approach are likely to // roll scores in the middle, so would get prizes equal to // 1-10% of total prize funds. uint singleWinnerShare = totalPrizeAmount / cfg.prizeSequence_winnerCount; return totalPrizeAmount - rankingPosition * singleWinnerShare; } // Now, we know that ending algorithm is normal (deterministic). // So, compute the prizes in a standard way. // If using Computed Sequence: loop for "rankingPosition" // iterations, while computing the prize shares. // If "rankingPosition" is larger than sequencedWinnerCount, // then compute the prize from sequence-leftover amount. if( cfg.prizeSequenceFactor != 0 ) { require( rankingPosition < cfg.prizeSequence_winnerCount/*, "Invalid ranking position!" */); // Leftover: If prizeSequenceFactor is 25%, it's 75%. uint leftoverPercentage = (_100PERCENT) - cfg.prizeSequenceFactor; // Loop until the needed iteration. uint loopCount = ( rankingPosition >= cfg.prizeSequence_sequencedWinnerCount ? cfg.prizeSequence_sequencedWinnerCount : rankingPosition ); for( uint i = 0; i < loopCount; i++ ) { totalPrizeAmount = ( totalPrizeAmount * leftoverPercentage ) / ( _100PERCENT ); } // Get end prize amount - sequenced, or leftover. // Leftover-mode. if( loopCount == cfg.prizeSequence_sequencedWinnerCount && cfg.prizeSequence_winnerCount > cfg.prizeSequence_sequencedWinnerCount ) { // Now, totalPrizeAmount equals all leftover-group winner // prize funds. // So, just divide it by number of leftover winners. finalPrizeAmount = ( totalPrizeAmount ) / ( cfg.prizeSequence_winnerCount - cfg.prizeSequence_sequencedWinnerCount ); } // Sequenced-mode else { finalPrizeAmount = ( totalPrizeAmount * cfg.prizeSequenceFactor ) / ( _100PERCENT ); } } // Else, if we're using Pre-Specified Array of winner profit // shares, just get the share at the corresponding index. else { require( rankingPosition < cfg.winnerProfitShares.length ); finalPrizeAmount = ( totalPrizeAmount * cfg.winnerProfitShares[ rankingPosition ] ) / ( _100PERCENT ); } } /** * After lottery has completed, this function returns if msg.sender * is one of lottery winners, and the position in winner rankings. * * Function must be used to obtain the ranking position before * calling claimWinnerPrize(). * * @param addr - address whose status to check. */ function getWinnerStatus( address addr ) external view returns( bool isWinner, uint32 rankingPosition, uint prizeAmount ) { if( !onStage( STAGE.COMPLETION ) || balanceOf( addr ) == 0 ) return (false , 0, 0); ( isWinner, rankingPosition ) = lotStorage.getWinnerStatus( addr ); if( isWinner ) { prizeAmount = getWinnerPrizeAmount( rankingPosition ); if( prizeAmount > address(this).balance ) prizeAmount = address(this).balance; } } /** * Compute the intermediate Active Stage player score. * This score is Player Score, not randomized. * @param addr - address to check. */ function getPlayerIntermediateScore( address addr ) external view returns( uint ) { return lotStorage.getPlayerActiveStageScore( addr ); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Claim the winner prize of msg.sender, if he is one of the winners. * * This function must be provided a ranking position of msg.sender, * which must be obtained using the function above. * * The Lottery Storage then just checks if holder address in the * winner array element at position rankingPosition is the same * as msg.sender's. * * If so, then claim request is valid, and we can give the appropriate * prize to that winner. * Prize can be determined by a computed factor-based sequence, or * from the pre-specified winner array. * * * This function transfers Ether out of our contract: * - Sends the corresponding winner prize to the msg.sender. * * @param rankingPosition - the position of Winner Array, that * msg.sender says he is in (obtained using getWinnerStatus). */ function claimWinnerPrize( uint32 rankingPosition ) external onlyOnStage( STAGE.COMPLETION ) mutexLOCKED { // Check if msg.sender hasn't already claimed his prize. require( ! prizeClaimersAddresses[ msg.sender ]/*, "msg.sender has already claimed his prize!" */); // msg.sender must have at least some of UniLottery Tokens. require( balanceOf( msg.sender ) != 0/*, "msg.sender's token balance can't be zero!" */); // Check if there are any prize funds left yet. require( address(this).balance != 0/*, "All prize funds have already been claimed!" */); // If using Mined Selection Algo, check if msg.sender is // really on that ranking position - algo was already executed. if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) ) { require( lotStorage.minedSelection_isAddressOnWinnerPosition( msg.sender, rankingPosition )/*, "msg.sender is not on specified winner position!" */); } // For other algorithms, get ranking position by executing // a specific algorithm of that algo-type. else { bool isWinner; ( isWinner, rankingPosition ) = lotStorage.getWinnerStatus( msg.sender ); require( isWinner/*, "msg.sender is not a winner!" */); } // Compute the prize amount, using our internal function. uint finalPrizeAmount = getWinnerPrizeAmount( rankingPosition ); // If prize is small and computation precision errors occured, // leading it to be larger than our balance, fix it. if( finalPrizeAmount > address(this).balance ) finalPrizeAmount = address(this).balance; // Transfer the Winning Prize to msg.sender! msg.sender.transfer( finalPrizeAmount ); // Mark msg.sender as already claimed his prize. prizeClaimersAddresses[ msg.sender ] = true; } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Transfer the leftover Winner Prize Funds of this contract to the * Main UniLottery Pool, if prize claim deadline has been exceeded. * * Function can only be called from the Main Pool, and if some * winners haven't managed to claim their prizes on time, their * prizes will go back to UniLottery Pool. * * * Function transfers Ether out of our contract: * - Transfer the leftover funds to the Pool (msg.sender). */ function getUnclaimedPrizes() external poolOnly onlyOnStage( STAGE.COMPLETION ) mutexLOCKED { // Check if prize claim deadline has passed. require( completionDate != 0 && ( block.timestamp - completionDate ) > cfg.prizeClaimTime/*, "Prize claim deadline not reached yet!" */); // Just transfer it all to the Pool. poolAddress.transfer( address(this).balance ); } } contract UniLotteryRandomnessProvider is usingProvable { // =============== E-Vent Section =============== // // New Lottery Random Seed Request made. event LotteryRandomSeedRequested( uint id, address lotteryAddress, uint gasLimit, uint totalEtherGiven ); // Random seed obtained, and callback successfully completed. event LotteryRandomSeedCallbackCompleted( uint id ); // UniLottery Pool scheduled a call. event PoolCallbackScheduled( uint id, address poolAddress, uint timeout, uint gasLimit, uint totalEtherGiven ); // Pool scheduled callback successfully completed. event PoolCallbackCompleted( uint id ); // Ether transfered into fallback. event EtherTransfered( address sender, uint value ); // =============== Structs & Enums =============== // // Enum - type of the request. enum RequestType { LOTTERY_RANDOM_SEED, POOL_SCHEDULED_CALLBACK } // Call Request Structure. struct CallRequestData { // -------- Slot -------- // // The ID of the request. uint256 requestID; // -------- Slot -------- // // Requester address. Can be pool, or an ongoing lottery. address requesterAddress; // The Type of request (Random Seed or Pool Scheduled Callback). RequestType reqType; } // Lottery request config - specifies gas limits that must // be used for that specific lottery's callback. // Must be set separately from CallRequest, because gas required // is specified and funds are transfered by The Pool, before starting // a lottery, and when that lottery ends, it just calls us, expecting // it's gas cost funds to be already sent to us. struct LotteryGasConfig { // -------- Slot -------- // // The total ether funds that the pool has transfered to // our contract for execution of this lottery's callback. uint160 etherFundsTransferedForGas; // The gas limit provided for that callback. uint64 gasLimit; } // =============== State Variables =============== // // -------- Slot -------- // // Mapping of all currently pending or on-process requests // from their Query IDs. mapping( uint256 => CallRequestData ) pendingRequests; // -------- Slot -------- // // A mapping of Pool-specified-before-their-start lottery addresses, // to their corresponding Gas Configs, which will be used for // their end callbacks. mapping( address => LotteryGasConfig ) lotteryGasConfigs; // -------- Slot -------- // // The Pool's address. We receive funds from it, and use it // to check whether the requests are coming from ongoing lotteries. address payable poolAddress; // ============ Private/Internal Functions ============ // // Pool-Only modifier. modifier poolOnly { require( msg.sender == poolAddress/*, "Function can only be called by the Main Pool!" */); _; } // Ongoing Lottery Only modifier. // Data must be fetch'd from the Pool. modifier ongoingLotteryOnly { require( IMainUniLotteryPool( poolAddress ) .isLotteryOngoing( msg.sender )/*, "Function can be called only by ongoing lotteries!" */); _; } // ================= Public Functions ================= // /** * Constructor. * Here, we specify the Provable proof type, to use for * Random Datasource queries. */ constructor() { // Set the Provable proof type for Random Queries - Ledger. provable_setProof( proofType_Ledger ); } /** * Initialization function. * Called by the Pool, on Pool's constructor, to initialize this * randomness provider. */ function initialize() external { // Check if we were'nt initialized yet (pool address not set yet). require( poolAddress == address( 0 )/*, "Contract is already initialized!" */); poolAddress = msg.sender; } /** * The Payable Fallback function. * This function is used by the Pool, to transfer the required * funds to us, to be able to pay for Provable gas & fees. */ receive () external payable { emit EtherTransfered( msg.sender, msg.value ); } /** * Get the total Ether price for a request to specific * datasource with specific gas limit. * It just calls the Provable's internal getPrice function. */ // Random datasource. function getPriceForRandomnessCallback( uint gasLimit ) external returns( uint totalEtherPrice ) { return provable_getPrice( "random", gasLimit ); } // URL datasource (for callback scheduling). function getPriceForScheduledCallback( uint gasLimit ) external returns( uint totalEtherPrice ) { return provable_getPrice( "URL", gasLimit ); } /** * Set the gas limit which should be used by the lottery deployed * on address "lotteryAddr", when that lottery finishes and * requests us to call it's ending callback with random seed * provided. * Also, specify the amount of Ether that the pool has transfered * to us for the execution of this lottery's callback. */ function setLotteryCallbackGas( address lotteryAddr, uint64 callbackGasLimit, uint160 totalEtherTransferedForThisOne ) external poolOnly { LotteryGasConfig memory gasConfig; gasConfig.gasLimit = callbackGasLimit; gasConfig.etherFundsTransferedForGas = totalEtherTransferedForThisOne; // Set the mapping entry for this lottery address. lotteryGasConfigs[ lotteryAddr ] = gasConfig; } /** * The Provable Callback, which will get called from Off-Chain * Provable service, when it completes execution of our request, * made before previously with provable_query variant. * * Here, we can perform 2 different tasks, based on request type * (we get the CallRequestData from the ID passed by Provable). * * The different tasks are: * 1. Pass Random Seed to Lottery Ending Callback. * 2. Call a Pool's Scheduled Callback. */ function __callback( bytes32 _queryId, string memory _result, bytes memory _proof ) public override { // Check that the sender is Provable Services. require( msg.sender == provable_cbAddress() ); // Get the Request Data storage pointer, and check if it's Set. CallRequestData storage reqData = pendingRequests[ uint256( _queryId ) ]; require( reqData.requestID != 0/*, "Invalid Request Data structure (Response is Invalid)!" */); // Check the Request Type - if it's a lottery asking for a // random seed, or a Pool asking to call it's scheduled callback. if( reqData.reqType == RequestType.LOTTERY_RANDOM_SEED ) { // It's a lottery asking for a random seed. // Check if Proof is valid, using the Base Contract's built-in // checking functionality. require( provable_randomDS_proofVerify__returnCode( _queryId, _result, _proof ) == 0/*, "Random Datasource Proof Verification has FAILED!" */); // Get the Random Number by keccak'ing the random bytes passed. uint256 randomNumber = uint256( keccak256( abi.encodePacked( _result ) ) ); // Pass this Random Number as a Seed to the requesting lottery! ILottery( reqData.requesterAddress ) .finish_randomnessProviderCallback( randomNumber, uint( _queryId ) ); // Emit appropriate events. emit LotteryRandomSeedCallbackCompleted( uint( _queryId ) ); } // It's a pool, asking to call it's callback, that it scheduled // to get called in some time before. else if( reqData.reqType == RequestType.POOL_SCHEDULED_CALLBACK ) { IMainUniLotteryPool( poolAddress ) .scheduledCallback( uint( _queryId ) ); // Emit appropriate events. emit PoolCallbackCompleted( uint( _queryId ) ); } // We're finished! Remove the request data from the pending // requests mapping. delete pendingRequests[ uint256( _queryId ) ]; } /** * This is the function through which the Lottery requests a * Random Seed for it's ending callback. * The gas funds needed for that callback's execution were already * transfered to us from The Pool, at the moment the Pool created * and deployed that lottery. * The gas specifications are set in the LotteryGasConfig of that * specific lottery. * TODO: Also set the custom gas price. */ function requestRandomSeedForLotteryFinish() external ongoingLotteryOnly returns( uint256 requestId ) { // Check if gas limit (amount of gas) for this lottery was set. require( lotteryGasConfigs[ msg.sender ].gasLimit != 0/*, "Gas limit for this lottery was not set!" */); // Check if the currently estimated price for this request // is not higher than the one that the pool transfered funds for. uint transactionPrice = provable_getPrice( "random", lotteryGasConfigs[ msg.sender ].gasLimit ); if( transactionPrice > lotteryGasConfigs[ msg.sender ].etherFundsTransferedForGas ) { // If our balance is enough to execute the transaction, then // ask pool if it agrees that we execute this transaction // with higher price than pool has given funds to us for. if( address(this).balance >= transactionPrice ) { bool response = IMainUniLotteryPool( poolAddress ) .onLotteryCallbackPriceExceedingGivenFunds( msg.sender, transactionPrice, lotteryGasConfigs[msg.sender].etherFundsTransferedForGas ); require( response/*, "Pool has denied the request!" */); } // If price absolutely exceeds our contract's balance: else { require( false/*, "Request price exceeds contract's balance!" */); } } // Set the Provable Query parameters. // Execute the query as soon as possible. uint256 QUERY_EXECUTION_DELAY = 0; // Set the gas amount to the previously specified gas limit. uint256 GAS_FOR_CALLBACK = lotteryGasConfigs[ msg.sender ].gasLimit; // Request 8 random bytes (that's enough randomness with keccak). uint256 NUM_RANDOM_BYTES_REQUESTED = 8; // Execute the Provable Query! uint256 queryId = uint256( provable_newRandomDSQuery( QUERY_EXECUTION_DELAY, NUM_RANDOM_BYTES_REQUESTED, GAS_FOR_CALLBACK ) ); // Populate & Add the pending requests mapping entry. CallRequestData memory requestData; requestData.requestID = queryId; requestData.reqType = RequestType.LOTTERY_RANDOM_SEED; requestData.requesterAddress = msg.sender; pendingRequests[ queryId ] = requestData; // Emit an event - lottery just requested a random seed. emit LotteryRandomSeedRequested( queryId, msg.sender, lotteryGasConfigs[ msg.sender ].gasLimit, lotteryGasConfigs[ msg.sender ].etherFundsTransferedForGas ); // Remove the just-used Lottery Gas Configs mapping entry. delete lotteryGasConfigs[ msg.sender ]; // Return the ID of the query. return queryId; } /** * Schedule a call for the pool, using specified amount of gas, * and executing after specified amount of time. * Accomplished using an empty URL query, and setting execution * delay to the specified timeout. * On execution, __callback() calls the Pool's scheduledCallback() * function. * * @param timeout - how much time to delay the execution of callback. * @param gasLimit - gas limit to use for the callback's execution. * @param etherFundsTransferedForGas - how much Ether has the Pool * transfered to our contract before calling this function, * to be used only for this operation. */ function schedulePoolCallback( uint timeout, uint gasLimit, uint etherFundsTransferedForGas ) external poolOnly returns( uint256 requestId ) { // Price exceeding transfered funds doesn't need to be checked // here, because pool transfers required funds just before // calling this function, so price can't change between transfer // and this function's call. // Execute the query on specified timeout, with a // specified Gas Limit. uint queryId = uint( provable_query( timeout, "URL", "", gasLimit ) ); // Populate & Add the pending requests mapping entry. CallRequestData memory requestData; requestData.requestID = queryId; requestData.reqType = RequestType.POOL_SCHEDULED_CALLBACK; requestData.requesterAddress = msg.sender; pendingRequests[ queryId ] = requestData; // Emit an event - lottery just requested a random seed. emit PoolCallbackScheduled( queryId, poolAddress, timeout, gasLimit, etherFundsTransferedForGas ); // Return a query ID. return queryId; } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Sends the specified amount of Ether back to the Pool. * WARNING: Future Provable requests might fail due to insufficient * funds! No checks are made to ensure sufficiency. */ function sendFundsToPool( uint etherAmount ) external poolOnly { poolAddress.transfer( etherAmount ); } /** * Set the gas price to be used for future Provable queries. * Used to change the default gas in times of congested networks. */ function setGasPrice( uint _gasPrice ) external poolOnly { // Limit gas price to 600 GWei. require( _gasPrice <= 600 * (10 ** 9)/*, "Specified gas price is higher than 600 GWei !" */); provable_setCustomGasPrice( _gasPrice ); } }
Check if msg.sender hasn't already claimed his prize. msg.sender must have at least some of UniLottery Tokens. Check if there are any prize funds left yet. If using Mined Selection Algo, check if msg.sender is really on that ranking position - algo was already executed.
function claimWinnerPrize( uint32 rankingPosition ) external onlyOnStage( STAGE.COMPLETION ) mutexLOCKED { require( ! prizeClaimersAddresses[ msg.sender ]/*, "msg.sender has already claimed his prize!" */); require( balanceOf( msg.sender ) != 0/*, "msg.sender's token balance can't be zero!" */); require( address(this).balance != 0/*, "All prize funds have already been claimed!" */); if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) ) { require( lotStorage.minedSelection_isAddressOnWinnerPosition( msg.sender, rankingPosition )/*, "msg.sender is not on specified winner position!" */); } else { bool isWinner; ( isWinner, rankingPosition ) = lotStorage.getWinnerStatus( msg.sender ); require( isWinner/*, "msg.sender is not a winner!" */); } uint finalPrizeAmount = getWinnerPrizeAmount( rankingPosition ); if( finalPrizeAmount > address(this).balance ) finalPrizeAmount = address(this).balance; msg.sender.transfer( finalPrizeAmount ); prizeClaimersAddresses[ msg.sender ] = true; }
7,579,047
./partial_match/1/0xa25E8050F80eE99A17E861CD0931D5D362CAA34E/sources/GameCards.sol
Get lease from card
function getLease(uint8 cardId, uint leaseId) public view returns(uint leaseIndex, address tenant, uint untilBlock, string title, string url, string image) { return( cardDetailsStructs[cardId].leaseCardStructs[leaseId].id, cardDetailsStructs[cardId].leaseCardStructs[leaseId].tenant, cardDetailsStructs[cardId].leaseCardStructs[leaseId].untilBlock, cardDetailsStructs[cardId].leaseCardStructs[leaseId].title, cardDetailsStructs[cardId].leaseCardStructs[leaseId].url, cardDetailsStructs[cardId].leaseCardStructs[leaseId].image ); }
4,222,112
./full_match/4/0x7dD946c95152d0872DB3f1f866F582E1805D6c75/sources/browser/TokenESJ-v2.1.sol
Force moves `value` tokens from the ``from``'s account to ``to``'s account. - reserved to `BANKER_ROLE`./
function transferInternal(address from, address to, uint256 value) public { require(hasRole(BANKER_ROLE, _msgSender()), "ERC20 transfer: must have banker role to transfer others' tokens"); _transfer(from, to, value); }
667,440