file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity 0.5.16; /* is IERC20 */ interface IERC4626Vault { /// @notice The address of the underlying token used for the Vault uses for accounting, depositing, and withdrawing function asset() external view returns (address assetTokenAddress); /// @notice Total amount of the underlying asset that is β€œmanaged” by Vault function totalAssets() external view returns (uint256 totalManagedAssets); /** * @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met. * @param assets The amount of underlying assets to be convert to vault shares. * @return shares The amount of vault shares converted from the underlying assets. */ function convertToShares(uint256 assets) external view returns (uint256 shares); /** * @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met. * @param shares The amount of vault shares to be converted to the underlying assets. * @return assets The amount of underlying assets converted from the vault shares. */ function convertToAssets(uint256 shares) external view returns (uint256 assets); /** * @notice The maximum number of underlying assets that caller can deposit. * @param caller Account that the assets will be transferred from. * @return maxAssets The maximum amount of underlying assets the caller can deposit. */ function maxDeposit(address caller) external view returns (uint256 maxAssets); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be transferred. * @return shares The amount of vault shares that will be minted. */ function previewDeposit(uint256 assets) external view returns (uint256 shares); /** * @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller. * @param assets The amount of underlying assets to be transferred to the vault. * @param receiver The account that the vault shares will be minted to. * @return shares The amount of vault shares that were minted. */ function deposit(uint256 assets, address receiver) external returns (uint256 shares); /** * @notice The maximum number of vault shares that caller can mint. * @param caller Account that the underlying assets will be transferred from. * @return maxShares The maximum amount of vault shares the caller can mint. */ function maxMint(address caller) external view returns (uint256 maxShares); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be minted. * @return assets The amount of underlying assests that will be transferred from the caller. */ function previewMint(uint256 shares) external view returns (uint256 assets); /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @return assets The amount of underlying assets that were transferred from the caller. */ function mint(uint256 shares, address receiver) external returns (uint256 assets); /** * @notice The maximum number of underlying assets that owner can withdraw. * @param owner Account that owns the vault shares. * @return maxAssets The maximum amount of underlying assets the owner can withdraw. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be withdrawn. * @return shares The amount of vault shares that will be burnt. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares); /** * @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver. * @param assets The amount of underlying assets to be withdrawn from the vault. * @param receiver The account that the underlying assets will be transferred to. * @param owner Account that owns the vault shares to be burnt. * @return shares The amount of vault shares that were burnt. */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares); /** * @notice The maximum number of shares an owner can redeem for underlying assets. * @param owner Account that owns the vault shares. * @return maxShares The maximum amount of shares the owner can redeem. */ function maxRedeem(address owner) external view returns (uint256 maxShares); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be burnt. * @return assets The amount of underlying assests that will transferred to the receiver. */ function previewRedeem(uint256 shares) external view returns (uint256 assets); /** * @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver. * @param shares The amount of vault shares to be burnt. * @param receiver The account the underlying assets will be transferred to. * @param owner The account that owns the vault shares to be burnt. * @return assets The amount of underlying assets that were transferred to the receiver. */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); /*/////////////////////////////////////////////////////////////// Events //////////////////////////////////////////////////////////////*/ /** * @dev Emitted when caller has exchanged assets for shares, and transferred those shares to owner. * * Note It must be emitted when tokens are deposited into the Vault in ERC4626.mint or ERC4626.deposit methods. * */ event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); /** * @dev Emitted when sender has exchanged shares for assets, and transferred those assets to receiver. * * Note It must be emitted when shares are withdrawn from the Vault in ERC4626.redeem or ERC4626.withdraw methods. * */ event Withdraw( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); } interface IUnwrapper { // @dev Get bAssetOut status function getIsBassetOut( address _masset, bool _inputIsCredit, address _output ) external view returns (bool isBassetOut); /// @dev Estimate output function getUnwrapOutput( bool _isBassetOut, address _router, address _input, bool _inputIsCredit, address _output, uint256 _amount ) external view returns (uint256 output); /// @dev Unwrap and send function unwrapAndSend( bool _isBassetOut, address _router, address _input, address _output, uint256 _amount, uint256 _minAmountOut, address _beneficiary ) external returns (uint256 outputQuantity); } interface ISavingsManager { /** @dev Admin privs */ function distributeUnallocatedInterest(address _mAsset) external; /** @dev Liquidator */ function depositLiquidation(address _mAsset, uint256 _liquidation) external; /** @dev Liquidator */ function collectAndStreamInterest(address _mAsset) external; /** @dev Public privs */ function collectAndDistributeInterest(address _mAsset) external; } interface ISavingsContractV1 { function depositInterest(uint256 _amount) external; function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); function redeem(uint256 _amount) external returns (uint256 massetReturned); function exchangeRate() external view returns (uint256); function creditBalances(address) external view returns (uint256); } interface ISavingsContractV4 { // DEPRECATED but still backwards compatible function redeem(uint256 _amount) external returns (uint256 massetReturned); function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf) // -------------------------------------------- function depositInterest(uint256 _amount) external; // V1 & V2 function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2 function depositSavings(uint256 _amount, address _beneficiary) external returns (uint256 creditsIssued); // V2 function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2 function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2 function exchangeRate() external view returns (uint256); // V1 & V2 function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2 function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2 function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2 // -------------------------------------------- function redeemAndUnwrap( uint256 _amount, bool _isCreditAmt, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut ) external returns ( uint256 creditsBurned, uint256 massetRedeemed, uint256 outputQuantity ); function depositSavings( uint256 _underlying, address _beneficiary, address _referrer ) external returns (uint256 creditsIssued); // -------------------------------------------- V4 function deposit( uint256 assets, address receiver, address referrer ) external returns (uint256 shares); function mint( uint256 shares, address receiver, address referrer ) external returns (uint256 assets); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance") ); } } contract InitializableERC20Detailed 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. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract InitializableToken is ERC20, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } contract InitializableModule2 is ModuleKeys { INexus public constant nexus = INexus(0xAFcE80b19A8cE13DEc0739a1aaB7A028d6845Eb3); /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } interface IConnector { /** * @notice Deposits the mAsset into the connector * @param _amount Units of mAsset to receive and deposit */ function deposit(uint256 _amount) external; /** * @notice Withdraws a specific amount of mAsset from the connector * @param _amount Units of mAsset to withdraw */ function withdraw(uint256 _amount) external; /** * @notice Withdraws all mAsset from the connector */ function withdrawAll() external; /** * @notice Returns the available balance in the connector. In connections * where there is likely to be an initial dip in value due to conservative * exchange rates (e.g. with Curves `get_virtual_price`), it should return * max(deposited, balance) to avoid temporary negative yield. Any negative yield * should be corrected during a withdrawal or over time. * @return Balance of mAsset in the connector */ function checkBalance() external view returns (uint256); } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require( initializing || isConstructor() || !initialized, "Contract instance has already been initialized" ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * @dev bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x.mul(FULL_SCALE); } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x.mul(ratio); // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled.add(RATIO_SCALE.sub(1)); // return 100..00.999e8 / 1e8 = 1e18 return ceil.div(RATIO_SCALE); } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 uint256 y = x.mul(RATIO_SCALE); // return 1e22 / 1e12 = 1e10 return y.div(ratio); } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } /** * @title SavingsContract * @author Stability Labs Pty. Ltd. * @notice Savings contract uses the ever increasing "exchangeRate" to increase * the value of the Savers "credits" (ERC20) relative to the amount of additional * underlying collateral that has been deposited into this contract ("interest") * @dev VERSION: 2.1 * DATE: 2021-11-25 */ contract SavingsContract_imusd_mainnet_22 is ISavingsContractV1, ISavingsContractV4, IERC4626Vault, Initializable, InitializableToken, InitializableModule2 { using SafeMath for uint256; using StableMath for uint256; // Core events for depositing and withdrawing event ExchangeRateUpdated(uint256 newExchangeRate, uint256 interestCollected); event SavingsDeposited(address indexed saver, uint256 savingsDeposited, uint256 creditsIssued); event CreditsRedeemed( address indexed redeemer, uint256 creditsRedeemed, uint256 savingsCredited ); event AutomaticInterestCollectionSwitched(bool automationEnabled); // Connector poking event PokerUpdated(address poker); event FractionUpdated(uint256 fraction); event ConnectorUpdated(address connector); event EmergencyUpdate(); event Poked(uint256 oldBalance, uint256 newBalance, uint256 interestDetected); event PokedRaw(); // Tracking events event Referral(address indexed referrer, address beneficiary, uint256 amount); // Rate between 'savings credits' and underlying // e.g. 1 credit (1e17) mulTruncate(exchangeRate) = underlying, starts at 10:1 // exchangeRate increases over time uint256 private constant startingRate = 1e17; uint256 public exchangeRate; // Underlying asset is underlying IERC20 public constant underlying = IERC20(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); bool private automateInterestCollection; // Yield // Poker is responsible for depositing/withdrawing from connector address public poker; // Last time a poke was made uint256 public lastPoke; // Last known balance of the connector uint256 public lastBalance; // Fraction of capital assigned to the connector (100% = 1e18) uint256 public fraction; // Address of the current connector (all IConnectors are mStable validated) IConnector public connector; // How often do we allow pokes uint256 private constant POKE_CADENCE = 4 hours; // Max APY generated on the capital in the connector uint256 private constant MAX_APY = 4e18; uint256 private constant SECONDS_IN_YEAR = 365 days; // Proxy contract for easy redemption address public constant unwrapper = 0xc1443Cb9ce81915fB914C270d74B0D57D1c87be0; uint256 private constant MAX_INT256 = 2**256 - 1; // Add these constants to bytecode at deploytime function initialize( address _poker, string calldata _nameArg, string calldata _symbolArg ) external initializer { InitializableToken._initialize(_nameArg, _symbolArg); require(_poker != address(0), "Invalid poker address"); poker = _poker; fraction = 2e17; automateInterestCollection = true; exchangeRate = startingRate; } /** @dev Only the savings managaer (pulled from Nexus) can execute this */ modifier onlySavingsManager() { require(msg.sender == _savingsManager(), "Only savings manager can execute"); _; } /*************************************** VIEW - E ****************************************/ /** * @dev Returns the underlying balance of a given user * @param _user Address of the user to check * @return balance Units of underlying owned by the user */ function balanceOfUnderlying(address _user) external view returns (uint256 balance) { (balance, ) = _creditsToUnderlying(balanceOf(_user)); } /** * @dev Converts a given underlying amount into credits * @param _underlying Units of underlying * @return credits Credit units (a.k.a imUSD) */ function underlyingToCredits(uint256 _underlying) external view returns (uint256 credits) { (credits, ) = _underlyingToCredits(_underlying); } /** * @dev Converts a given credit amount into underlying * @param _credits Units of credits * @return amount Corresponding underlying amount */ function creditsToUnderlying(uint256 _credits) external view returns (uint256 amount) { (amount, ) = _creditsToUnderlying(_credits); } // Deprecated in favour of `balanceOf(address)` // Maintained for backwards compatibility // Returns the credit balance of a given user function creditBalances(address _user) external view returns (uint256) { return balanceOf(_user); } /*************************************** INTEREST ****************************************/ /** * @dev Deposit interest (add to savings) and update exchange rate of contract. * Exchange rate is calculated as the ratio between new savings q and credits: * exchange rate = savings / credits * * @param _amount Units of underlying to add to the savings vault */ function depositInterest(uint256 _amount) external onlySavingsManager { require(_amount > 0, "Must deposit something"); // Transfer the interest from sender to here require(underlying.transferFrom(msg.sender, address(this), _amount), "Must receive tokens"); // Calc new exchange rate, protect against initialisation case uint256 totalCredits = totalSupply(); if (totalCredits > 0) { // new exchange rate is relationship between _totalCredits & totalSavings // _totalCredits * exchangeRate = totalSavings // exchangeRate = totalSavings/_totalCredits (uint256 totalCollat, ) = _creditsToUnderlying(totalCredits); uint256 newExchangeRate = _calcExchangeRate(totalCollat.add(_amount), totalCredits); exchangeRate = newExchangeRate; emit ExchangeRateUpdated(newExchangeRate, _amount); } } /** @dev Enable or disable the automation of fee collection during deposit process */ function automateInterestCollectionFlag(bool _enabled) external onlyGovernor { automateInterestCollection = _enabled; emit AutomaticInterestCollectionSwitched(_enabled); } /*************************************** DEPOSIT ****************************************/ /** * @dev During a migration period, allow savers to deposit underlying here before the interest has been redirected * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @return creditsIssued Units of credits (imUSD) issued */ function preDeposit(uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued) { require(exchangeRate == startingRate, "Can only use this method before streaming begins"); return _deposit(_underlying, _beneficiary, false); } /** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * @param _underlying Units of underlying to deposit into savings vault * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings(uint256 _underlying) external returns (uint256 creditsIssued) { return _deposit(_underlying, msg.sender, true); } /** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings(uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued) { return _deposit(_underlying, _beneficiary, true); } /** * @dev Overloaded `depositSavings` method with an optional referrer address. * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @param _referrer Referrer address for this deposit * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings( uint256 _underlying, address _beneficiary, address _referrer ) external returns (uint256 creditsIssued) { emit Referral(_referrer, _beneficiary, _underlying); return _deposit(_underlying, _beneficiary, true); } /** * @dev Internally deposit the _underlying from the sender and credit the beneficiary with new imUSD */ function _deposit( uint256 _underlying, address _beneficiary, bool _collectInterest ) internal returns (uint256 creditsIssued) { creditsIssued = _transferAndMint(_underlying, _beneficiary, _collectInterest); } /*************************************** REDEEM ****************************************/ // Deprecated in favour of redeemCredits // Maintaining backwards compatibility, this fn minimics the old redeem fn, in which // credits are redeemed but the interest from the underlying is not collected. function redeem(uint256 _credits) external returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); (, uint256 payout) = _redeem(_credits, true, true); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } return payout; } /** * @dev Redeem specific number of the senders "credits" in exchange for underlying. * Payout amount is calculated as a ratio of credits and exchange rate: * payout = credits * exchangeRate * @param _credits Amount of credits to redeem * @return massetReturned Units of underlying mAsset paid out */ function redeemCredits(uint256 _credits) external returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (, uint256 payout) = _redeem(_credits, true, true); return payout; } /** * @dev Redeem credits into a specific amount of underlying. * Credits needed to burn is calculated using: * credits = underlying / exchangeRate * @param _underlying Amount of underlying to redeem * @return creditsBurned Units of credits burned from sender */ function redeemUnderlying(uint256 _underlying) external returns (uint256 creditsBurned) { require(_underlying > 0, "Must withdraw something"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } // Ensure that the payout was sufficient (uint256 credits, uint256 massetReturned) = _redeem(_underlying, false, true); require(massetReturned == _underlying, "Invalid output"); return credits; } /** * @notice Redeem credits into a specific amount of underlying, unwrap * into a selected output asset, and send to a beneficiary * Credits needed to burn is calculated using: * credits = underlying / exchangeRate * @param _amount Units to redeem (either underlying or credit amount). * @param _isCreditAmt `true` if `amount` is in credits. eg imUSD. `false` if `amount` is in underlying. eg mUSD. * @param _minAmountOut Minimum amount of `output` tokens to unwrap for. This is to the same decimal places as the `output` token. * @param _output Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example: - bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault. - bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault. - bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault. * @param _beneficiary Address to send `output` tokens to. * @param _router mAsset address if the output is a bAsset. Feeder Pool address if the output is a fAsset. * @param _isBassetOut `true` if `output` is a bAsset. `false` if `output` is a fAsset. * @return creditsBurned Units of credits burned from sender. eg imUSD or imBTC. * @return massetReturned Units of the underlying mAssets that were redeemed or swapped for the output tokens. eg mUSD or mBTC. * @return outputQuantity Units of `output` tokens sent to the beneficiary. */ function redeemAndUnwrap( uint256 _amount, bool _isCreditAmt, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut ) external returns ( uint256 creditsBurned, uint256 massetReturned, uint256 outputQuantity ) { require(_amount > 0, "Must withdraw something"); require(_output != address(0), "Output address is zero"); require(_beneficiary != address(0), "Beneficiary address is zero"); require(_router != address(0), "Router address is zero"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } // Ensure that the payout was sufficient (creditsBurned, massetReturned) = _redeem(_amount, _isCreditAmt, false); require( _isCreditAmt ? creditsBurned == _amount : massetReturned == _amount, "Invalid output" ); // Approve wrapper to spend contract's underlying; just for this tx underlying.approve(unwrapper, massetReturned); // Unwrap the underlying into `output` and transfer to `beneficiary` outputQuantity = IUnwrapper(unwrapper).unwrapAndSend( _isBassetOut, _router, address(underlying), _output, massetReturned, _minAmountOut, _beneficiary ); } /** * @dev Internally burn the credits and send the underlying to msg.sender */ function _redeem( uint256 _amt, bool _isCreditAmt, bool _transferUnderlying ) internal returns (uint256 creditsBurned, uint256 massetReturned) { // Centralise credit <> underlying calcs and minimise SLOAD count uint256 credits_; uint256 underlying_; uint256 exchangeRate_; // If the input is a credit amt, then calculate underlying payout and cache the exchangeRate if (_isCreditAmt) { credits_ = _amt; (underlying_, exchangeRate_) = _creditsToUnderlying(_amt); } // If the input is in underlying, then calculate credits needed to burn else { underlying_ = _amt; (credits_, exchangeRate_) = _underlyingToCredits(_amt); } _burnTransfer( underlying_, credits_, msg.sender, msg.sender, exchangeRate_, _transferUnderlying ); emit CreditsRedeemed(msg.sender, credits_, underlying_); return (credits_, underlying_); } struct ConnectorStatus { // Limit is the max amount of units allowed in the connector uint256 limit; // Derived balance of the connector uint256 inConnector; } /** * @dev Derives the units of collateral held in the connector * @param _data Struct containing data on balances * @param _exchangeRate Current system exchange rate * @return status Contains max amount of assets allowed in connector */ function _getConnectorStatus(CachedData memory _data, uint256 _exchangeRate) internal pure returns (ConnectorStatus memory) { // Total units of underlying collateralised uint256 totalCollat = _data.totalCredits.mulTruncate(_exchangeRate); // Max amount of underlying that can be held in the connector uint256 limit = totalCollat.mulTruncate(_data.fraction.add(2e17)); // Derives amount of underlying present in the connector uint256 inConnector = _data.rawBalance >= totalCollat ? 0 : totalCollat.sub(_data.rawBalance); return ConnectorStatus(limit, inConnector); } /*************************************** YIELD - E ****************************************/ /** @dev Modifier allowing only the designated poker to execute the fn */ modifier onlyPoker() { require(msg.sender == poker, "Only poker can execute"); _; } /** * @dev External poke function allows for the redistribution of collateral between here and the * current connector, setting the ratio back to the defined optimal. */ function poke() external onlyPoker { CachedData memory cachedData = _cacheData(); _poke(cachedData, false); } /** * @dev Governance action to set the address of a new poker * @param _newPoker Address of the new poker */ function setPoker(address _newPoker) external onlyGovernor { require(_newPoker != address(0) && _newPoker != poker, "Invalid poker"); poker = _newPoker; emit PokerUpdated(_newPoker); } /** * @dev Governance action to set the percentage of assets that should be held * in the connector. * @param _fraction Percentage of assets that should be held there (where 20% == 2e17) */ function setFraction(uint256 _fraction) external onlyGovernor { require(_fraction <= 5e17, "Fraction must be <= 50%"); fraction = _fraction; CachedData memory cachedData = _cacheData(); _poke(cachedData, true); emit FractionUpdated(_fraction); } /** * @dev Governance action to set the address of a new connector, and move funds (if any) across. * @param _newConnector Address of the new connector */ function setConnector(address _newConnector) external onlyGovernor { // Withdraw all from previous by setting target = 0 CachedData memory cachedData = _cacheData(); cachedData.fraction = 0; _poke(cachedData, true); // Set new connector CachedData memory cachedDataNew = _cacheData(); connector = IConnector(_newConnector); _poke(cachedDataNew, true); emit ConnectorUpdated(_newConnector); } /** * @dev Governance action to perform an emergency withdraw of the assets in the connector, * should it be the case that some or all of the liquidity is trapped in. This causes the total * collateral in the system to go down, causing a hard refresh. */ function emergencyWithdraw(uint256 _withdrawAmount) external onlyGovernor { // withdraw _withdrawAmount from connection connector.withdraw(_withdrawAmount); // reset the connector connector = IConnector(address(0)); emit ConnectorUpdated(address(0)); // set fraction to 0 fraction = 0; emit FractionUpdated(0); // check total collateralisation of credits CachedData memory data = _cacheData(); // use rawBalance as the remaining liquidity in the connector is now written off _refreshExchangeRate(data.rawBalance, data.totalCredits, true); emit EmergencyUpdate(); } /*************************************** YIELD - I ****************************************/ /** @dev Internal poke function to keep the balance between connector and raw balance healthy */ function _poke(CachedData memory _data, bool _ignoreCadence) internal { require(_data.totalCredits > 0, "Must have something to poke"); // 1. Verify that poke cadence is valid, unless this is a manual action by governance uint256 currentTime = uint256(now); uint256 timeSinceLastPoke = currentTime.sub(lastPoke); require(_ignoreCadence || timeSinceLastPoke > POKE_CADENCE, "Not enough time elapsed"); lastPoke = currentTime; // If there is a connector, check the balance and settle to the specified fraction % IConnector connector_ = connector; if (address(connector_) != address(0)) { // 2. Check and verify new connector balance uint256 lastBalance_ = lastBalance; uint256 connectorBalance = connector_.checkBalance(); // Always expect the collateral in the connector to increase in value require(connectorBalance >= lastBalance_, "Invalid yield"); if (connectorBalance > 0) { // Validate the collection by ensuring that the APY is not ridiculous _validateCollection( connectorBalance, connectorBalance.sub(lastBalance_), timeSinceLastPoke ); } // 3. Level the assets to Fraction (connector) & 100-fraction (raw) uint256 sum = _data.rawBalance.add(connectorBalance); uint256 ideal = sum.mulTruncate(_data.fraction); // If there is not enough mAsset in the connector, then deposit if (ideal > connectorBalance) { uint256 deposit = ideal.sub(connectorBalance); underlying.approve(address(connector_), deposit); connector_.deposit(deposit); } // Else withdraw, if there is too much mAsset in the connector else if (connectorBalance > ideal) { // If fraction == 0, then withdraw everything if (ideal == 0) { connector_.withdrawAll(); sum = IERC20(underlying).balanceOf(address(this)); } else { connector_.withdraw(connectorBalance.sub(ideal)); } } // Else ideal == connectorBalance (e.g. 0), do nothing require(connector_.checkBalance() >= ideal, "Enforce system invariant"); // 4i. Refresh exchange rate and emit event lastBalance = ideal; _refreshExchangeRate(sum, _data.totalCredits, false); emit Poked(lastBalance_, ideal, connectorBalance.sub(lastBalance_)); } else { // 4ii. Refresh exchange rate and emit event lastBalance = 0; _refreshExchangeRate(_data.rawBalance, _data.totalCredits, false); emit PokedRaw(); } } /** * @dev Internal fn to refresh the exchange rate, based on the sum of collateral and the number of credits * @param _realSum Sum of collateral held by the contract * @param _totalCredits Total number of credits in the system * @param _ignoreValidation This is for use in the emergency situation, and ignores a decreasing exchangeRate */ function _refreshExchangeRate( uint256 _realSum, uint256 _totalCredits, bool _ignoreValidation ) internal { // Based on the current exchange rate, how much underlying is collateralised? (uint256 totalCredited, ) = _creditsToUnderlying(_totalCredits); // Require the amount of capital held to be greater than the previously credited units require(_ignoreValidation || _realSum >= totalCredited, "ExchangeRate must increase"); // Work out the new exchange rate based on the current capital uint256 newExchangeRate = _calcExchangeRate(_realSum, _totalCredits); exchangeRate = newExchangeRate; emit ExchangeRateUpdated( newExchangeRate, _realSum > totalCredited ? _realSum.sub(totalCredited) : 0 ); } /** * FORKED DIRECTLY FROM SAVINGSMANAGER.sol * --------------------------------------- * @dev Validates that an interest collection does not exceed a maximum APY. If last collection * was under 30 mins ago, simply check it does not exceed 10bps * @param _newBalance New balance of the underlying * @param _interest Increase in total supply since last collection * @param _timeSinceLastCollection Seconds since last collection */ function _validateCollection( uint256 _newBalance, uint256 _interest, uint256 _timeSinceLastCollection ) internal pure returns (uint256 extrapolatedAPY) { // Protect against division by 0 uint256 protectedTime = StableMath.max(1, _timeSinceLastCollection); uint256 oldSupply = _newBalance.sub(_interest); uint256 percentageIncrease = _interest.divPrecisely(oldSupply); uint256 yearsSinceLastCollection = protectedTime.divPrecisely(SECONDS_IN_YEAR); extrapolatedAPY = percentageIncrease.divPrecisely(yearsSinceLastCollection); if (protectedTime > 30 minutes) { require(extrapolatedAPY < MAX_APY, "Interest protected from inflating past maxAPY"); } else { require(percentageIncrease < 1e15, "Interest protected from inflating past 10 Bps"); } } /*************************************** VIEW - I ****************************************/ struct CachedData { // SLOAD from 'fraction' uint256 fraction; // ERC20 balance of underlying, held by this contract // underlying.balanceOf(address(this)) uint256 rawBalance; // totalSupply() uint256 totalCredits; } /** * @dev Retrieves generic data to avoid duplicate SLOADs */ function _cacheData() internal view returns (CachedData memory) { uint256 balance = underlying.balanceOf(address(this)); return CachedData(fraction, balance, totalSupply()); } /** * @dev Converts masset amount into credits based on exchange rate * c = (masset / exchangeRate) + 1 */ function _underlyingToCredits(uint256 _underlying) internal view returns (uint256 credits, uint256 exchangeRate_) { // e.g. (1e20 * 1e18) / 1e18 = 1e20 // e.g. (1e20 * 1e18) / 14e17 = 7.1429e19 // e.g. 1 * 1e18 / 1e17 + 1 = 11 => 11 * 1e17 / 1e18 = 1.1e18 / 1e18 = 1 exchangeRate_ = exchangeRate; credits = _underlying.divPrecisely(exchangeRate_).add(1); } /** * @dev Works out a new exchange rate, given an amount of collateral and total credits * e = underlying / (credits-1) */ function _calcExchangeRate(uint256 _totalCollateral, uint256 _totalCredits) internal pure returns (uint256 _exchangeRate) { _exchangeRate = _totalCollateral.divPrecisely(_totalCredits.sub(1)); } /** * @dev Converts credit amount into masset based on exchange rate * m = credits * exchangeRate */ function _creditsToUnderlying(uint256 _credits) internal view returns (uint256 underlyingAmount, uint256 exchangeRate_) { // e.g. (1e20 * 1e18) / 1e18 = 1e20 // e.g. (1e20 * 14e17) / 1e18 = 1.4e20 exchangeRate_ = exchangeRate; underlyingAmount = _credits.mulTruncate(exchangeRate_); } /*/////////////////////////////////////////////////////////////// IERC4626Vault //////////////////////////////////////////////////////////////*/ /** * @notice it must be an ERC-20 token contract. Must not revert. * * @return assetTokenAddress the address of the underlying asset token. eg mUSD or mBTC */ function asset() external view returns (address assetTokenAddress) { return address(underlying); } /** * @return totalManagedAssets the total amount of the underlying asset tokens that is β€œmanaged” by Vault. */ function totalAssets() external view returns (uint256 totalManagedAssets) { return underlying.balanceOf(address(this)); } /** * @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met. * @param assets The amount of underlying assets to be convert to vault shares. * @return shares The amount of vault shares converted from the underlying assets. */ function convertToShares(uint256 assets) external view returns (uint256 shares) { (shares, ) = _underlyingToCredits(assets); } /** * @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met. * @param shares The amount of vault shares to be converted to the underlying assets. * @return assets The amount of underlying assets converted from the vault shares. */ function convertToAssets(uint256 shares) external view returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); } /** * @notice The maximum number of underlying assets that caller can deposit. * caller Account that the assets will be transferred from. * @return maxAssets The maximum amount of underlying assets the caller can deposit. */ function maxDeposit( address /** caller **/ ) external view returns (uint256 maxAssets) { maxAssets = MAX_INT256; } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be transferred. * @return shares The amount of vault shares that will be minted. */ function previewDeposit(uint256 assets) external view returns (uint256 shares) { require(assets > 0, "Must deposit something"); (shares, ) = _underlyingToCredits(assets); } /** * @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller. * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * Emits a {Deposit} event. * @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC * @param receiver The address to receive the Vault shares. * @return shares Units of credits issued. eg imUSD or imBTC */ function deposit(uint256 assets, address receiver) external returns (uint256 shares) { shares = _transferAndMint(assets, receiver, true); } /** * * @notice Overloaded `deposit` method with an optional referrer address. * @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC * @param receiver Address to the new credits will be issued to. * @param referrer Referrer address for this deposit. * @return shares Units of credits issued. eg imUSD or imBTC */ function deposit( uint256 assets, address receiver, address referrer ) external returns (uint256 shares) { shares = _transferAndMint(assets, receiver, true); emit Referral(referrer, receiver, assets); } /** * @notice The maximum number of vault shares that caller can mint. * caller Account that the underlying assets will be transferred from. * @return maxShares The maximum amount of vault shares the caller can mint. */ function maxMint( address /* caller */ ) external view returns (uint256 maxShares) { maxShares = MAX_INT256; } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be minted. * @return assets The amount of underlying assests that will be transferred from the caller. */ function previewMint(uint256 shares) external view returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); return assets; } /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * Emits a {Deposit} event. * * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @return assets The amount of underlying assets that were transferred from the caller. */ function mint(uint256 shares, address receiver) external returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); _transferAndMint(assets, receiver, true); } /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @param referrer Referrer address for this deposit. * @return assets The amount of underlying assets that were transferred from the caller. * Emits a {Deposit}, {Referral} events */ function mint( uint256 shares, address receiver, address referrer ) external returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); _transferAndMint(assets, receiver, true); emit Referral(referrer, receiver, assets); } /** * @notice The maximum number of underlying assets that owner can withdraw. * @param owner Address that owns the underlying assets. * @return maxAssets The maximum amount of underlying assets the owner can withdraw. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets) { (maxAssets, ) = _creditsToUnderlying(balanceOf(owner)); } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be withdrawn. * @return shares The amount of vault shares that will be burnt. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares) { (shares, ) = _underlyingToCredits(assets); } /** * @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver. * Emits a {Withdraw} event. * * @param assets The amount of underlying assets to be withdrawn from the vault. * @param receiver The account that the underlying assets will be transferred to. * @param owner Account that owns the vault shares to be burnt. * @return shares The amount of vault shares that were burnt. */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares) { require(assets > 0, "Must withdraw something"); uint256 _exchangeRate; if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (shares, _exchangeRate) = _underlyingToCredits(assets); _burnTransfer(assets, shares, receiver, owner, _exchangeRate, true); } /** * @notice it must return a limited value if owner is subject to some withdrawal limit or timelock. must return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. MAY be used in the previewRedeem or redeem methods for shares input parameter. must NOT revert. * * @param owner Address that owns the shares. * @return maxShares Total number of shares that owner can redeem. */ function maxRedeem(address owner) external view returns (uint256 maxShares) { maxShares = balanceOf(owner); } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions. * * @return assets the exact amount of underlying assets that would be withdrawn by the caller if redeeming a given exact amount of Vault shares using the redeem method */ function previewRedeem(uint256 shares) external view returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); return assets; } /** * @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver. * Emits a {Withdraw} event. * * @param shares The amount of vault shares to be burnt. * @param receiver The account the underlying assets will be transferred to. * @param owner The account that owns the vault shares to be burnt. * @return assets The amount of underlying assets that were transferred to the receiver. */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets) { require(shares > 0, "Must withdraw something"); uint256 _exchangeRate; if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (assets, _exchangeRate) = _creditsToUnderlying(shares); _burnTransfer(assets, shares, receiver, owner, _exchangeRate, true); //transferAssets=true } /*/////////////////////////////////////////////////////////////// INTERNAL DEPOSIT/MINT //////////////////////////////////////////////////////////////*/ function _transferAndMint( uint256 assets, address receiver, bool _collectInterest ) internal returns (uint256 shares) { require(assets > 0, "Must deposit something"); require(receiver != address(0), "Invalid beneficiary address"); // Collect recent interest generated by basket and update exchange rate IERC20 mAsset = underlying; if (_collectInterest) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mAsset)); } // Transfer tokens from sender to here require(mAsset.transferFrom(msg.sender, address(this), assets), "Must receive tokens"); // Calc how many credits they receive based on currentRatio (shares, ) = _underlyingToCredits(assets); // add credits to ERC20 balances _mint(receiver, shares); emit Deposit(msg.sender, receiver, assets, shares); emit SavingsDeposited(receiver, assets, shares); } /*/////////////////////////////////////////////////////////////// INTERNAL WITHDRAW/REDEEM //////////////////////////////////////////////////////////////*/ function _burnTransfer( uint256 assets, uint256 shares, address receiver, address owner, uint256 _exchangeRate, bool transferAssets ) internal { require(receiver != address(0), "Invalid beneficiary address"); // If caller is not the owner of the shares uint256 allowed = allowance(owner, msg.sender); if (msg.sender != owner && allowed != MAX_INT256) { require(shares <= allowed, "Amount exceeds allowance"); _approve(owner, msg.sender, allowed - shares); } // Burn required shares from the owner FIRST _burn(owner, shares); // Optionally, transfer tokens from here to receiver if (transferAssets) { require(underlying.transfer(receiver, assets), "Must send tokens"); emit Withdraw(msg.sender, receiver, owner, assets, shares); } // If this withdrawal pushes the portion of stored collateral in the `connector` over a certain // threshold (fraction + 20%), then this should trigger a _poke on the connector. This is to avoid // a situation in which there is a rush on withdrawals for some reason, causing the connector // balance to go up and thus having too large an exposure. CachedData memory cachedData = _cacheData(); ConnectorStatus memory status = _getConnectorStatus(cachedData, _exchangeRate); if (status.inConnector > status.limit) { _poke(cachedData, false); } } }
* @dev During a migration period, allow savers to deposit underlying here before the interest has been redirected @param _underlying Units of underlying to deposit into savings vault @param _beneficiary Immediately transfer the imUSD token to this beneficiary address @return creditsIssued Units of credits (imUSD) issued/
function preDeposit(uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued) { require(exchangeRate == startingRate, "Can only use this method before streaming begins"); return _deposit(_underlying, _beneficiary, false); }
2,367,631
[ 1, 26424, 279, 6333, 3879, 16, 1699, 4087, 414, 358, 443, 1724, 6808, 2674, 1865, 326, 16513, 711, 2118, 21808, 225, 389, 9341, 6291, 1377, 27845, 434, 6808, 358, 443, 1724, 1368, 4087, 899, 9229, 225, 389, 70, 4009, 74, 14463, 814, 377, 2221, 7101, 7412, 326, 709, 3378, 40, 1147, 358, 333, 27641, 74, 14463, 814, 1758, 327, 6197, 1282, 7568, 5957, 282, 27845, 434, 6197, 1282, 261, 381, 3378, 40, 13, 16865, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 675, 758, 1724, 12, 11890, 5034, 389, 9341, 6291, 16, 1758, 389, 70, 4009, 74, 14463, 814, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 5034, 6197, 1282, 7568, 5957, 13, 203, 565, 288, 203, 3639, 2583, 12, 16641, 4727, 422, 5023, 4727, 16, 315, 2568, 1338, 999, 333, 707, 1865, 12833, 17874, 8863, 203, 3639, 327, 389, 323, 1724, 24899, 9341, 6291, 16, 389, 70, 4009, 74, 14463, 814, 16, 629, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.8; contract Coin { /* * @title A Simple Subcurrency Example * @author Toshendra Sharma * @notice Example for the Solidity Course * @dev This is only for demo the simple Coin example * */ address public minter; uint public totalCoins; event LogCoinsMinted(address deliveredTo, uint amount); event LogCoinsSent(address sentTo, uint amount); mapping (address => uint) balances; function Coin(uint initialCoins) { minter = msg.sender; totalCoins = initialCoins; balances[minter] = initialCoins; } /// @notice Mint the coins /// @dev This does not return any value /// @param owner address of the coin owner, amount amount of coins to be delivered to owner /// @return Nothing function mint(address owner, uint amount) { if (msg.sender != minter) return; balances[owner] += amount; totalCoins += amount; LogCoinsMinted(owner, amount); } function send(address receiver, uint amount) { if (balances[msg.sender] < amount) return; balances[msg.sender] -= amount; balances[receiver] += amount; LogCoinsSent(receiver, amount); } function queryBalance(address addr) constant returns (uint balance) { return balances[addr]; } function killCoin() returns (bool status) { if (msg.sender != minter) throw; selfdestruct(minter); } }
@notice Mint the coins @dev This does not return any value @param owner address of the coin owner, amount amount of coins to be delivered to owner @return Nothing
function mint(address owner, uint amount) { if (msg.sender != minter) return; balances[owner] += amount; totalCoins += amount; LogCoinsMinted(owner, amount); }
953,422
[ 1, 49, 474, 326, 276, 9896, 225, 1220, 1552, 486, 327, 1281, 460, 225, 3410, 1758, 434, 326, 13170, 3410, 16, 3844, 3844, 434, 276, 9896, 358, 506, 22112, 358, 3410, 327, 13389, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 3410, 16, 2254, 3844, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 1131, 387, 13, 327, 31, 203, 3639, 324, 26488, 63, 8443, 65, 1011, 3844, 31, 203, 3639, 2078, 39, 9896, 1011, 3844, 31, 203, 3639, 1827, 39, 9896, 49, 474, 329, 12, 8443, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-16 */ // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/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/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (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 // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/SmartContract.sol pragma solidity^0.8.0; contract SimpleMinter is ERC721Enumerable, Ownable { using Counters for Counters.Counter; using Strings for uint256; using SafeMath for uint256; string baseURI; // pointer for our nft image location string baseExtension = ".json"; uint256 price = 0.01 ether; // price of nft uint256 maxMintAmount= 1; // max per tx uint256 maxPerWallet = 5; // max per wallet uint256 maxSupply = 555; // total amount of nfts we have uint256 public startTime; Counters.Counter private _tokenTracker; constructor( // just a simple constructor string memory _baseUri, string memory _symbol, string memory _name, uint256 _startTime) ERC721(_name, _symbol) { setBaseURI(_baseUri); startTime = _startTime; } function setStartTime(uint256 _startTime) public onlyOwner { startTime = _startTime; } function setMaxTx(uint256 num) public onlyOwner { maxMintAmount = num; } function setBaseExtension(string memory _ext) public onlyOwner { baseExtension = _ext; } function setMaxWallet(uint256 num) public onlyOwner { maxPerWallet = num; } function setMaxSupply(uint256 num) public onlyOwner { maxSupply = num; } function setBaseURI(string memory _givenBaseURI) public onlyOwner { baseURI = _givenBaseURI; // set our baseURI to x } function _baseURI() internal override virtual view returns(string memory) { return baseURI; // retrieve our baseURI } function mint() public payable { uint256 alreadyMinted = totalSupply(); // see how many have already been minted require(alreadyMinted + 1 <= maxSupply, "We cannot supply this amount"); // check we have enough to mint uint256 userBal = balanceOf(msg.sender); require(userBal < maxPerWallet, "You are not allowed this many in one wallet"); require(block.timestamp >= startTime, "Sale is not live yet"); if (alreadyMinted >= 55) { require(msg.value >= price, "User did not send enough ether with this tx"); // check they are paying enough } else { require(userBal == 0, "You have minted the max amount during the free period"); } _safeMint(msg.sender, _tokenTracker.current()); // mint the user there nft _tokenTracker.increment(); } function tokenURI(uint256 tokenID) public view virtual override returns(string memory) { require(_exists(tokenID), "This token does not exist"); string memory currBaseURI = _baseURI(); return bytes(currBaseURI).length > 0 ? string(abi.encodePacked(currBaseURI, tokenID.toString(), baseExtension)):""; // for opensea and other places to find the data of our nft } function _widthdraw(address _address, uint256 _amount) internal { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } function withdrawAll() public onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "There is no funds to withdraw"); _widthdraw(0x43558232F2fD87c34F5a254f96493e55aBb89C50 , balance.mul(20).div(100)); // 20% _widthdraw(0xb82F051524Ff138ceac7A62184739D399D714388 , balance.mul(50).div(100)); // 50% _widthdraw(0x48D7B79a2b31C2ad4fE285F9F6De9a02033D12a1 , balance.mul(20).div(100)); // 20% _widthdraw(0xfA86599BBAc7e2B2A32922D575d38DA31E27Ca6F , balance.mul(10).div(100)); // 10% _widthdraw(0xb82F051524Ff138ceac7A62184739D399D714388, address(this).balance); // anything else (this should never be reached) } }
see how many have already been minted
uint256 alreadyMinted = totalSupply();
15,088,543
[ 1, 5946, 3661, 4906, 1240, 1818, 2118, 312, 474, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 1818, 49, 474, 329, 273, 2078, 3088, 1283, 5621, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xC001647e18571F4513993Ce648C3E33534906b98/sources/Master.sol
* @title Mau's Master @dev Controller for an elastic supply currency based on the uFragments Ideal Money protocol a.k.a. Ampleforth. uFragments operates symmetrically on expansion and contraction. It will both split and combine coins to maintain a stable unit price. This component regulates the token supply of the uFragments ERC20 token in response to market oracles./
contract Master is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); event LogRebase( uint256 indexed epoch, uint256 exchangeRate, int256 requestedSupplyAdjustment, uint256 timestampSec ); IMau public mau; uint256 private constant DECIMALS = 18; uint256 public targetRate; int256 public posDamp; int256 public negDamp; bool public posRebaseEnabled; bool public rebaseLocked; Transaction[] public transactions; IOracle public marketOracle; uint256 public deviationThreshold; uint256 public rebaseCooldown; uint256 public lastRebaseTimestampSec; uint256 public epoch; uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; constructor(address _mau) public { deviationThreshold = 5 * 10 ** (DECIMALS-2); targetRate = (5508 * 10 ** (DECIMALS-14)); negDamp = 2; posDamp = 20; rebaseCooldown = 8 hours; lastRebaseTimestampSec = block.timestamp + rebaseCooldown; epoch = 1; rebaseLocked = true; posRebaseEnabled = true; mau = IMau(_mau); } function releaseOwnership() public onlyOwner { require(!rebaseLocked, "Cannot renounce ownership if rebase is locked"); super.renounceOwnership(); } function setRebaseLocked(bool _locked) external onlyOwner { rebaseLocked = _locked; } function setPosRebaseEnabled() external onlyOwner { posRebaseEnabled = true; } function setPosRebaseDisabled() external onlyOwner { posRebaseEnabled = false; } function canRebase() public view returns (bool) { return ((!rebaseLocked || isOwner()) && lastRebaseTimestampSec.add(rebaseCooldown) < now); } function cooldownExpiryTimestamp() public view returns (uint256) { return lastRebaseTimestampSec.add(rebaseCooldown); } function rebase() external { require(tx.origin == msg.sender); require(canRebase(), "Rebase not allowed"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 exchangeRate, int256 supplyDelta) = getRebaseValues(); if (supplyDelta > 0 && !posRebaseEnabled) { supplyDelta = 0; } uint256 supplyAfterRebase = mau.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } marketOracle.update(); if (epoch < 80) { incrementTargetRate(); finalRate(); } emit LogRebase(epoch, exchangeRate, supplyDelta, now); } function rebase() external { require(tx.origin == msg.sender); require(canRebase(), "Rebase not allowed"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 exchangeRate, int256 supplyDelta) = getRebaseValues(); if (supplyDelta > 0 && !posRebaseEnabled) { supplyDelta = 0; } uint256 supplyAfterRebase = mau.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } marketOracle.update(); if (epoch < 80) { incrementTargetRate(); finalRate(); } emit LogRebase(epoch, exchangeRate, supplyDelta, now); } function rebase() external { require(tx.origin == msg.sender); require(canRebase(), "Rebase not allowed"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 exchangeRate, int256 supplyDelta) = getRebaseValues(); if (supplyDelta > 0 && !posRebaseEnabled) { supplyDelta = 0; } uint256 supplyAfterRebase = mau.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } marketOracle.update(); if (epoch < 80) { incrementTargetRate(); finalRate(); } emit LogRebase(epoch, exchangeRate, supplyDelta, now); } function rebase() external { require(tx.origin == msg.sender); require(canRebase(), "Rebase not allowed"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 exchangeRate, int256 supplyDelta) = getRebaseValues(); if (supplyDelta > 0 && !posRebaseEnabled) { supplyDelta = 0; } uint256 supplyAfterRebase = mau.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } marketOracle.update(); if (epoch < 80) { incrementTargetRate(); finalRate(); } emit LogRebase(epoch, exchangeRate, supplyDelta, now); } function rebase() external { require(tx.origin == msg.sender); require(canRebase(), "Rebase not allowed"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 exchangeRate, int256 supplyDelta) = getRebaseValues(); if (supplyDelta > 0 && !posRebaseEnabled) { supplyDelta = 0; } uint256 supplyAfterRebase = mau.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } marketOracle.update(); if (epoch < 80) { incrementTargetRate(); finalRate(); } emit LogRebase(epoch, exchangeRate, supplyDelta, now); } function rebase() external { require(tx.origin == msg.sender); require(canRebase(), "Rebase not allowed"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 exchangeRate, int256 supplyDelta) = getRebaseValues(); if (supplyDelta > 0 && !posRebaseEnabled) { supplyDelta = 0; } uint256 supplyAfterRebase = mau.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } marketOracle.update(); if (epoch < 80) { incrementTargetRate(); finalRate(); } emit LogRebase(epoch, exchangeRate, supplyDelta, now); } } else { function incrementTargetRate() internal { targetRate = targetRate.mul(6).div(5); } function finalRate() internal { targetRate = ( 1 ** (DECIMALS-4)); } function setPosDampFactor(int256 pdf) external onlyOwner { posDamp = pdf; } function setNegDampFactor(int256 ndf) external onlyOwner { negDamp = ndf; } function getRebaseValues() public view returns (uint256, int256) { uint256 exchangeRate = marketOracle.getData(); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate); if (supplyDelta < 0) { supplyDelta = supplyDelta.div(negDamp); supplyDelta = supplyDelta.div(posDamp); } if (supplyDelta > 0 && mau.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(mau.totalSupply())).toInt256Safe(); } return (exchangeRate, supplyDelta); } function getRebaseValues() public view returns (uint256, int256) { uint256 exchangeRate = marketOracle.getData(); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate); if (supplyDelta < 0) { supplyDelta = supplyDelta.div(negDamp); supplyDelta = supplyDelta.div(posDamp); } if (supplyDelta > 0 && mau.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(mau.totalSupply())).toInt256Safe(); } return (exchangeRate, supplyDelta); } function getRebaseValues() public view returns (uint256, int256) { uint256 exchangeRate = marketOracle.getData(); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate); if (supplyDelta < 0) { supplyDelta = supplyDelta.div(negDamp); supplyDelta = supplyDelta.div(posDamp); } if (supplyDelta > 0 && mau.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(mau.totalSupply())).toInt256Safe(); } return (exchangeRate, supplyDelta); } } else { function getRebaseValues() public view returns (uint256, int256) { uint256 exchangeRate = marketOracle.getData(); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate); if (supplyDelta < 0) { supplyDelta = supplyDelta.div(negDamp); supplyDelta = supplyDelta.div(posDamp); } if (supplyDelta > 0 && mau.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(mau.totalSupply())).toInt256Safe(); } return (exchangeRate, supplyDelta); } function computeSupplyDelta(uint256 rate) internal view returns (int256) { if (withinDeviationThreshold(rate)) { return 0; } int256 targetRateSigned = targetRate.toInt256Safe(); return mau.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } function computeSupplyDelta(uint256 rate) internal view returns (int256) { if (withinDeviationThreshold(rate)) { return 0; } int256 targetRateSigned = targetRate.toInt256Safe(); return mau.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } function withinDeviationThreshold(uint256 rate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } function addTransaction(address destination, bytes calldata data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } function addTransaction(address destination, bytes calldata data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } require(transactions.length > 0, "transactions list is empty"); transactions[transactions.length - 1] = Transaction(false, address(0), ""); } function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } require(transactions.length > 0, "transactions list is empty"); transactions[transactions.length - 1] = Transaction(false, address(0), ""); } function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } function transactionsSize() external view returns (uint256) { return transactions.length; } function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; let outputAddress := mload(0x40) let dataAddress := add(data, 32) result := call( sub(gas(), 34710), destination, dataAddress, outputAddress, ) } return result; }
3,886,180
[ 1, 49, 8377, 1807, 13453, 225, 6629, 364, 392, 10465, 14467, 5462, 2511, 603, 326, 582, 27588, 23062, 287, 16892, 1771, 279, 18, 79, 18, 69, 18, 432, 1291, 298, 1884, 451, 18, 1377, 582, 27588, 2255, 815, 15108, 1230, 603, 17965, 471, 16252, 1128, 18, 2597, 903, 3937, 1416, 471, 1377, 8661, 276, 9896, 358, 17505, 279, 14114, 2836, 6205, 18, 1377, 1220, 1794, 960, 17099, 326, 1147, 14467, 434, 326, 582, 27588, 4232, 39, 3462, 1147, 316, 766, 358, 1377, 13667, 578, 69, 9558, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 13453, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 1702, 364, 509, 5034, 31, 203, 565, 1450, 29810, 5034, 5664, 364, 2254, 5034, 31, 203, 203, 565, 1958, 5947, 288, 203, 3639, 1426, 3696, 31, 203, 3639, 1758, 2929, 31, 203, 3639, 1731, 501, 31, 203, 565, 289, 203, 203, 565, 871, 5947, 2925, 12, 2867, 8808, 2929, 16, 2254, 770, 16, 1731, 501, 1769, 203, 203, 203, 565, 871, 1827, 426, 1969, 12, 203, 3639, 2254, 5034, 8808, 7632, 16, 203, 3639, 2254, 5034, 7829, 4727, 16, 203, 3639, 509, 5034, 3764, 3088, 1283, 19985, 16, 203, 3639, 2254, 5034, 2858, 2194, 203, 565, 11272, 203, 203, 565, 6246, 8377, 1071, 312, 8377, 31, 203, 203, 203, 203, 203, 203, 203, 565, 2254, 5034, 3238, 5381, 25429, 55, 273, 6549, 31, 203, 203, 203, 565, 2254, 5034, 1071, 1018, 4727, 31, 203, 565, 509, 5034, 1071, 949, 40, 931, 31, 203, 565, 509, 5034, 1071, 4251, 40, 931, 31, 203, 377, 203, 565, 1426, 1071, 949, 426, 1969, 1526, 31, 203, 565, 1426, 1071, 283, 1969, 8966, 31, 7010, 203, 565, 5947, 8526, 1071, 8938, 31, 203, 565, 1665, 16873, 1071, 13667, 23601, 31, 203, 565, 2254, 5034, 1071, 17585, 7614, 31, 203, 565, 2254, 5034, 1071, 283, 1969, 39, 1371, 2378, 31, 203, 565, 2254, 5034, 1071, 1142, 426, 1969, 4921, 2194, 31, 203, 565, 2254, 5034, 1071, 7632, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 24062, 273, 1728, 2 ]
// SPDX-License-Identifier: MIT /* Pumpty Dumpty sat on a wall Pumpty Dumpty had a great fall All the king's horses and all the king's men Couldn't put Pumpty together again Sell limits are in place to make this the greatest Pump & Dump of all time. Emphasis on pump. Limits will be removed on the way up. Max Buy: 500000000 (.5%) : Will be raised to 1% shortly after launch. Max Wallet: 1000000000 (1%) Buys 8% Marketing Tax 2% Liquidity Tax Sells 10% Marketing Tax 2% Liquidity Tax */ pragma solidity 0.8.11; 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 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 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } 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"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _createInitialSupply(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } 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); } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() external virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IDexRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } interface IDexFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } contract PumptyDumpty is ERC20, Ownable { uint256 public maxBuyAmount; uint256 public maxSellAmount; uint256 public maxWalletAmount; IDexRouter public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; uint256 public swapTokensAtAmount; address public marketingAddress; address public rewardsAddress; uint256 public tradingActiveBlock = 0; // 0 means trading is not active 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 buyRewardsFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellrewardsFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForRewards; /******************/ // 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 SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event EnabledTrading(); event RemovedLimits(); event ExcludeFromFees(address indexed account, bool isExcluded); event UpdatedMaxBuyAmount(uint256 newAmount); event UpdatedMaxSellAmount(uint256 newAmount); event UpdatedMaxWalletAmount(uint256 newAmount); event UpdatedMarketingAddress(address indexed newWallet); event UpdatedRewardsAddress(address indexed newWallet); event MaxTransactionExclusion(address _address, bool excluded); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event TransferForeignToken(address token, uint256 amount); constructor() ERC20("Pumpty Dumpty", "PUMPTY") { address newOwner = msg.sender; // can leave alone if owner is deployer. IDexRouter _uniswapV2Router = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IDexFactory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 totalSupply = 100 * 1e9 * 1e18; maxBuyAmount = totalSupply * 5 / 1000; maxSellAmount = totalSupply * 1 / 1000; maxWalletAmount = totalSupply * 10 / 1000; swapTokensAtAmount = totalSupply * 25 / 100000; // 0.025% swap amount buyMarketingFee = 8; buyLiquidityFee = 2; buyRewardsFee = 0; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyRewardsFee; sellMarketingFee = 10; sellLiquidityFee = 2; sellrewardsFee = 0; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellrewardsFee; marketingAddress = address(0xE0a62e03d9c3ff7D87983e45A938a100b46F7F4F); rewardsAddress = address(0xE0a62e03d9c3ff7D87983e45A938a100b46F7F4F); _excludeFromMaxTransaction(newOwner, true); _excludeFromMaxTransaction(address(this), true); _excludeFromMaxTransaction(address(0xdead), true); excludeFromFees(newOwner, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); _createInitialSupply(newOwner, totalSupply); transferOwnership(newOwner); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { require(!tradingActive, "Cannot re enable trading"); tradingActive = true; swapEnabled = true; tradingActiveBlock = block.number; emit EnabledTrading(); } // remove limits after token is stable function removeLimits() external onlyOwner { limitsInEffect = false; transferDelayEnabled = false; emit RemovedLimits(); } // disable Transfer delay - cannot be re enabled function disableTransferDelay() external onlyOwner { transferDelayEnabled = false; } function updateMaxBuyAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set max buy amount lower than 0.1%"); maxBuyAmount = newNum * (10**18); emit UpdatedMaxBuyAmount(maxBuyAmount); } function updateMaxSellAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set max sell amount lower than 0.1%"); maxSellAmount = newNum * (10**18); emit UpdatedMaxSellAmount(maxSellAmount); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 3 / 1000)/1e18, "Cannot set max wallet amount lower than 0.3%"); maxWalletAmount = newNum * (10**18); emit UpdatedMaxWalletAmount(maxWalletAmount); } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply."); swapTokensAtAmount = newAmount; } function _excludeFromMaxTransaction(address updAds, bool isExcluded) private { _isExcludedMaxTransactionAmount[updAds] = isExcluded; emit MaxTransactionExclusion(updAds, isExcluded); } function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner { if(!isEx){ require(updAds != uniswapV2Pair, "Cannot remove uniswap pair from max txn"); } _isExcludedMaxTransactionAmount[updAds] = isEx; } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _excludeFromMaxTransaction(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _rewardsFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyRewardsFee = _rewardsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyRewardsFee; require(buyTotalFees <= 15, "Must keep fees at 15% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _rewardsFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellrewardsFee = _rewardsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellrewardsFee; require(sellTotalFees <= 30, "Must keep fees at 20% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } 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"); require(amount > 0, "amount must be greater than 0"); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead)){ if(!tradingActive){ require(_isExcludedMaxTransactionAmount[from] || _isExcludedMaxTransactionAmount[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 != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 4 && _holderLastTransferTimestamp[to] < block.number - 4, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to] && !_isExcludedMaxTransactionAmount[from]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; uint256 penaltyAmount = 0; // only take fees on Trades, not on wallet transfers if(takeFee){ // bot/sniper penalty. Tokens get transferred to marketing wallet and ETH to liquidity. if(tradingActiveBlock>0 && (tradingActiveBlock + 1) > block.number){ penaltyAmount = amount * 99 / 100; super._transfer(from, marketingAddress, penaltyAmount); } // on sell else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees /100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; tokensForRewards += fees * sellrewardsFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; tokensForRewards += fees * buyRewardsFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees + penaltyAmount; } 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 address(owner()), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForRewards; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 10){ contractBalance = swapTokensAtAmount * 10; } bool success; // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForMarketing = ethBalance * tokensForMarketing / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForRewards = ethBalance * tokensForRewards / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForMarketing + ethForRewards; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForRewards = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } (success,) = address(rewardsAddress).call{value: ethForRewards}(""); (success,) = address(marketingAddress).call{value: address(this).balance}(""); } function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } // withdraw ETH if stuck or someone sends to the address function withdrawStuckETH() external onlyOwner { bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } function setMarketingAddress(address _marketingAddress) external onlyOwner { require(_marketingAddress != address(0), "_marketingAddress address cannot be 0"); marketingAddress = payable(_marketingAddress); emit UpdatedMarketingAddress(_marketingAddress); } function setRewardsAddress(address _rewardsAddress) external onlyOwner { require(_rewardsAddress != address(0), "_rewardsAddress address cannot be 0"); rewardsAddress = payable(_rewardsAddress); emit UpdatedRewardsAddress(_rewardsAddress); } }
withdraw ETH if stuck or someone sends to the address
function withdrawStuckETH() external onlyOwner { bool success; }
371,264
[ 1, 1918, 9446, 512, 2455, 309, 384, 9031, 578, 18626, 9573, 358, 326, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 510, 9031, 1584, 44, 1435, 3903, 1338, 5541, 288, 203, 3639, 1426, 2216, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./Ownable.sol"; contract TellorData { /*TellorStorage*/ address public tellorStorageOwner;//TellorStorage Owner address /*TellorStorage*/ address public tellorContract;//Tellor address /*Variables Tellor*/ /*Tellor*/ bytes32 public currentChallenge; //current challenge to be solved /*Tellor*/ bytes32 public apiOnQ; //string of current api with highest PayoutPool not currently being mined /*DisputesAndVoting*/ uint8 public constant decimals = 18;//18 decimal standard ERC20 /*DisputesAndVoting*/ uint constant public disputeFee = 1e18;//cost to dispute a mined value /*TokenAndStaking*/ uint public total_supply; //total_supply of the token in circulation /*TokenAndStaking*/ uint constant public stakeAmt = 1000e18;//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) /*TokenAndStaking*/ uint public stakers; //number of parties currently staked /*Tellor*/ uint public timeOfLastProof = now - now % timeTarget; // time of last challenge solved /*Tellor*/ uint256 public difficulty_level = 1; // Difficulty of current block /*Tellor*/ uint public apiIdOnQ; // apiId of the on queue request /*Tellor*/ uint public apiOnQPayout; //value of highest api/timestamp PayoutPool /*Tellor*/ uint public miningApiId; //API being mined--updates with the ApiOnQ Id /*Tellor*/ uint public requests; // total number of requests through the system /*Tellor*/ uint public count;//Number of miners who have mined this value so far /*Tellor*/ uint constant public payoutTotal = 22e18;//Mining Reward in PoWo tokens given to all miners per value /*Tellor*/ uint constant public timeTarget = 10 * 60; //The time between blocks (mined Oracle values) /*Tellor*/ uint[5] public payoutStructure = [1e18,5e18,10e18,5e18,1e18];//The structure of the payout (how much uncles vs winner recieve) /*Tellor*/ uint[51] public payoutPool; //uint50 array of the top50 requests by payment amount /*Tellor*/ uint[] public timestamps; //array of all timestamps requested /*DisputesAndVoting*/ uint[] public disputesIds; //array of all disputes /*Tellor*/ mapping(bytes32 => mapping(address=>bool)) miners;//This is a boolean that tells you if a given challenge has been completed by a given miner /*Tellor*/ mapping(uint => uint) timeToApiId;//minedTimestamp to apiId /*Tellor*/ mapping(uint => uint) payoutPoolIndexToApiId; //link from payoutPoolIndex (position in payout pool array) to apiId /*DisputesAndVoting*/ mapping(uint => Dispute) disputes;//disputeId=> Dispute details /*DisputesAndVoting*/ mapping(bytes32 => uint) apiId;// api bytes32 gets an id = to count of requests array /*TokenAndStaking*/ mapping (address => Checkpoint[]) balances; //balances of a party given blocks /*TokenAndStaking*/ mapping(address => mapping (address => uint)) internal allowed; //allowance for a given party and approver /*TokenAndStaking*/ mapping(address => StakeInfo) staker;//mapping from a persons address to their staking info /*DisputesAndVoting*/ mapping(uint => API) apiDetails;//mapping of apiID to details /*DisputesAndVoting*/mapping(uint => address) propForkAddress;//maps proposalID to struct propFork /*DisputesAndVoting*/ string public constant name = "Tellor Tributes"; //name of the Token /*DisputesAndVoting*/ string public constant symbol = "TT";//Token Symbol /*Tellor*/ Details[5] public first_five; //This struct is for organizing the five mined values to find the median /*Tellor*/ struct Details { uint value; address miner; } /*DisputesAndVoting*/ struct Dispute { bool executed;//is the dispute settled bool disputeVotePassed;//did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty;//miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes uint apiId;//apiID of disputed value uint timestamp;//timestamp of distputed value uint value; //the value being disputed uint minExecutionDate;//7 days from when dispute initialized uint numberOfVotes;//the number of parties who have voted on the measure uint blockNumber;// the blocknumber for which votes will be calculated from uint index; //index in dispute array uint quorum; //quorum for dispute vote NEW int tally;//current tally of votes for - against measure mapping (address => bool) voted; //mapping of address to whether or not they voted } /*TokenAndStaking*/ struct StakeInfo { uint current_state;//1=started, 2=LockedForWithdraw 3= OnDispute uint startDate; //stake start date } /*TokenAndStaking*/ struct Checkpoint { uint128 fromBlock;// fromBlock is the block number that the value was generated from uint128 value;// value is the amount of tokens at a specific block number } /*DisputesAndVoting*/ struct API{ string apiString;//id to string api bytes32 apiHash;//hash of string uint index; //index in payoutPool uint payout;//current payout of the api, zeroed once mined mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number mapping(uint => uint) values;//This the time series of values stored by the contract where uint UNIX timestamp is mapped to value mapping(uint => address[5]) minersbyvalue; } /*Variables ownable*/ /*Ownable*/ address private _owner;//Tellor Owner address }
maps proposalID to struct propFork
/*DisputesAndVoting*/mapping(uint => address) propForkAddress;
1,803,142
[ 1, 10711, 14708, 734, 358, 1958, 2270, 22662, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1748, 1669, 458, 281, 1876, 58, 17128, 5549, 6770, 12, 11890, 516, 1758, 13, 2270, 22662, 1887, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.6.0; pragma experimental ABIEncoderV2; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import "./utils/Deployer.sol"; import "./interfaces/IERC721Template.sol"; import "OpenZeppelin/[email protected]//contracts/access/Ownable.sol"; import "./interfaces/IERC20Template.sol"; /** * @title DTFactory contract * @author Ocean Protocol Team * * @dev Implementation of Ocean DataTokens Factory * * DTFactory deploys DataToken proxy contracts. * New DataToken proxy contracts are links to the template contract's bytecode. * Proxy contract functionality is based on Ocean Protocol custom implementation of ERC1167 standard. */ contract ERC721Factory is Deployer, Ownable { address private communityFeeCollector; uint256 private currentNFTCount; address private erc20Factory; uint256 private nftTemplateCount; struct Template { address templateAddress; bool isActive; } mapping(uint256 => Template) public nftTemplateList; mapping(uint256 => Template) public templateList; mapping(address => address) public erc721List; mapping(address => bool) public erc20List; event NFTCreated( address indexed newTokenAddress, address indexed templateAddress, string tokenName, address admin, string symbol, string tokenURI ); uint256 private currentTokenCount = 0; uint256 public templateCount; address public router; event Template721Added(address indexed _templateAddress, uint256 indexed nftTemplateCount); event Template20Added(address indexed _templateAddress, uint256 indexed nftTemplateCount); //stored here only for ABI reasons event TokenCreated( address indexed newTokenAddress, address indexed templateAddress, string name, string symbol, uint256 cap, address creator ); event NewPool( address poolAddress, address ssContract, address basetokenAddress ); event NewFixedRate(bytes32 exchangeId, address owner); event DispenserCreated( // emited when a dispenser is created address indexed datatokenAddress, address indexed owner, uint256 maxTokens, uint256 maxBalance, address allowedSwapper ); /** * @dev constructor * Called on contract deployment. Could not be called with zero address parameters. * @param _template refers to the address of a deployed DataToken contract. * @param _collector refers to the community fee collector address * @param _router router contract address */ constructor( address _template721, address _template, address _collector, address _router ) { require( _template != address(0) && _collector != address(0) && _template721 != address(0), "ERC721DTFactory: Invalid template token/community fee collector address" ); add721TokenTemplate(_template721); addTokenTemplate(_template); router = _router; communityFeeCollector = _collector; } /** * @dev deployERC721Contract * * @param name NFT name * @param symbol NFT Symbol * @param _templateIndex template index we want to use * @param additionalERC20Deployer if != address(0), we will add it with ERC20Deployer role */ function deployERC721Contract( string memory name, string memory symbol, uint256 _templateIndex, address additionalERC20Deployer, string memory tokenURI ) public returns (address token) { require( _templateIndex <= nftTemplateCount && _templateIndex != 0, "ERC721DTFactory: Template index doesnt exist" ); Template memory tokenTemplate = nftTemplateList[_templateIndex]; require( tokenTemplate.isActive == true, "ERC721DTFactory: ERC721Token Template disabled" ); token = deploy(tokenTemplate.templateAddress); require( token != address(0), "ERC721DTFactory: Failed to perform minimal deploy of a new token" ); erc721List[token] = token; IERC721Template tokenInstance = IERC721Template(token); require( tokenInstance.initialize( msg.sender, name, symbol, address(this), additionalERC20Deployer, tokenURI ), "ERC721DTFactory: Unable to initialize token instance" ); emit NFTCreated(token, tokenTemplate.templateAddress, name, msg.sender, symbol, tokenURI); currentNFTCount += 1; } /** * @dev get the current token count. * @return the current token count */ function getCurrentNFTCount() external view returns (uint256) { return currentNFTCount; } /** * @dev get the token template Object * @param _index template Index * @return the template struct */ function getNFTTemplate(uint256 _index) external view returns (Template memory) { Template memory template = nftTemplateList[_index]; return template; } /** * @dev add a new NFT Template. Only Factory Owner can call it * @param _templateAddress new template address * @return the actual template count */ function add721TokenTemplate(address _templateAddress) public onlyOwner returns (uint256) { require( _templateAddress != address(0), "ERC721DTFactory: ERC721 template address(0) NOT ALLOWED" ); require(isContract(_templateAddress), "ERC721Factory: NOT CONTRACT"); nftTemplateCount += 1; Template memory template = Template(_templateAddress, true); nftTemplateList[nftTemplateCount] = template; emit Template721Added(_templateAddress,nftTemplateCount); return nftTemplateCount; } /** * @dev reactivate a disabled NFT Template. Only Factory Owner can call it * @param _index index we want to reactivate */ // function to activate a disabled token. function reactivate721TokenTemplate(uint256 _index) external onlyOwner { require( _index <= nftTemplateCount && _index != 0, "ERC721DTFactory: Template index doesnt exist" ); Template storage template = nftTemplateList[_index]; template.isActive = true; } /** * @dev disable an NFT Template. Only Factory Owner can call it * @param _index index we want to disable */ function disable721TokenTemplate(uint256 _index) external onlyOwner { require( _index <= nftTemplateCount && _index != 0, "ERC721DTFactory: Template index doesnt exist" ); Template storage template = nftTemplateList[_index]; template.isActive = false; } function getCurrentNFTTemplateCount() external view returns (uint256) { return nftTemplateCount; } /** * @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; } struct tokenStruct{ string[] strings; address[] addresses; uint256[] uints; bytes[] bytess; address owner; } /** * @dev Deploys new DataToken proxy contract. * This function is not called directly from here. It's called from the NFT contract. An NFT contract can deploy multiple ERC20 tokens. * @param _templateIndex ERC20Template index * @param strings refers to an array of strings * [0] = name * [1] = symbol * @param addresses refers to an array of addresses * [0] = minter account who can mint datatokens (can have multiple minters) * [1] = feeManager initial feeManager for this DT * [2] = publishing Market Address * [3] = publishing Market Fee Token * @param uints refers to an array of uints * [0] = cap_ the total ERC20 cap * [1] = publishing Market Fee Amount * @param bytess refers to an array of bytes, not in use now, left for future templates * @return token address of a new proxy DataToken contract */ function createToken( uint256 _templateIndex, string[] memory strings, address[] memory addresses, uint256[] memory uints, bytes[] memory bytess ) public returns (address token) { require( erc721List[msg.sender] == msg.sender, "ERC721Factory: ONLY ERC721 INSTANCE FROM ERC721FACTORY" ); token = _createToken(_templateIndex, strings, addresses, uints, bytess, msg.sender); } function _createToken( uint256 _templateIndex, string[] memory strings, address[] memory addresses, uint256[] memory uints, bytes[] memory bytess, address owner ) internal returns (address token) { require(uints[0] != 0, "ERC20Factory: zero cap is not allowed"); require( _templateIndex <= templateCount && _templateIndex != 0, "ERC20Factory: Template index doesnt exist" ); Template memory tokenTemplate = templateList[_templateIndex]; require( tokenTemplate.isActive == true, "ERC20Factory: ERC721Token Template disabled" ); token = deploy(tokenTemplate.templateAddress); erc20List[token] = true; require( token != address(0), "ERC721Factory: Failed to perform minimal deploy of a new token" ); emit TokenCreated(token, tokenTemplate.templateAddress, strings[0], strings[1], uints[0], owner); currentTokenCount += 1; tokenStruct memory tokenData; tokenData.strings = strings; tokenData.addresses = addresses; tokenData.uints = uints; tokenData.owner = owner; tokenData.bytess = bytess; _createTokenStep2(token, tokenData); } function _createTokenStep2(address token, tokenStruct memory tokenData) internal { IERC20Template tokenInstance = IERC20Template(token); address[] memory factoryAddresses = new address[](3); factoryAddresses[0] = tokenData.owner; factoryAddresses[1] = communityFeeCollector; factoryAddresses[2] = router; require( tokenInstance.initialize( tokenData.strings, tokenData.addresses, factoryAddresses, tokenData.uints, tokenData.bytess ), "ERC20Factory: Unable to initialize token instance" ); } /** * @dev get the current ERC20token deployed count. * @return the current token count */ function getCurrentTokenCount() external view returns (uint256) { return currentTokenCount; } /** * @dev get the current ERC20token template. @param _index template Index * @return the token Template Object */ function getTokenTemplate(uint256 _index) external view returns (Template memory) { Template memory template = templateList[_index]; require( _index <= templateCount && _index != 0, "ERC20Factory: Template index doesnt exist" ); return template; } /** * @dev add a new ERC20Template. Only Factory Owner can call it * @param _templateAddress new template address * @return the actual template count */ function addTokenTemplate(address _templateAddress) public onlyOwner returns (uint256) { require( _templateAddress != address(0), "ERC20Factory: ERC721 template address(0) NOT ALLOWED" ); require(isContract(_templateAddress), "ERC20Factory: NOT CONTRACT"); templateCount += 1; Template memory template = Template(_templateAddress, true); templateList[templateCount] = template; emit Template20Added(_templateAddress, templateCount); return templateCount; } /** * @dev disable an ERC20Template. Only Factory Owner can call it * @param _index index we want to disable */ function disableTokenTemplate(uint256 _index) external onlyOwner { Template storage template = templateList[_index]; template.isActive = false; } /** * @dev reactivate a disabled ERC20Template. Only Factory Owner can call it * @param _index index we want to reactivate */ // function to activate a disabled token. function reactivateTokenTemplate(uint256 _index) external onlyOwner { require( _index <= templateCount && _index != 0, "ERC20DTFactory: Template index doesnt exist" ); Template storage template = templateList[_index]; template.isActive = true; } // if templateCount is public we could remove it, or set templateCount to private function getCurrentTemplateCount() external view returns (uint256) { return templateCount; } struct tokenOrder { address tokenAddress; address consumer; uint256 amount; uint256 serviceId; address consumeFeeAddress; address consumeFeeToken; // address of the token marketplace wants to add fee on top uint256 consumeFeeAmount; } /** * @dev startMultipleTokenOrder * Used as a proxy to order multiple services * Users can have inifinite approvals for fees for factory instead of having one approval/ erc20 contract * Requires previous approval of all : * - consumeFeeTokens * - publishMarketFeeTokens * - erc20 datatokens * @param orders an array of struct tokenOrder */ function startMultipleTokenOrder( tokenOrder[] memory orders ) external { uint256 ids = orders.length; // TO DO. We can do better here , by groupping publishMarketFeeTokens and consumeFeeTokens and have a single // transfer for each one, instead of doing it per dt.. for (uint256 i = 0; i < ids; i++) { (address publishMarketFeeAddress, address publishMarketFeeToken, uint256 publishMarketFeeAmount) = IERC20Template(orders[i].tokenAddress).getPublishingMarketFee(); // check if we have publishFees, if so transfer them to us and approve dttemplate to take them if (publishMarketFeeAmount > 0 && publishMarketFeeToken!=address(0) && publishMarketFeeAddress!=address(0)) { require(IERC20Template(publishMarketFeeToken).transferFrom( msg.sender, address(this), publishMarketFeeAmount ),'Failed to transfer publishFee'); IERC20Template(publishMarketFeeToken).approve(orders[i].tokenAddress, publishMarketFeeAmount); } // check if we have consumeFees, if so transfer them to us and approve dttemplate to take them if (orders[i].consumeFeeAmount > 0 && orders[i].consumeFeeToken!=address(0) && orders[i].consumeFeeAddress!=address(0)) { require(IERC20Template(orders[i].consumeFeeToken).transferFrom( msg.sender, address(this), orders[i].consumeFeeAmount ),'Failed to transfer consumeFee'); IERC20Template(orders[i].consumeFeeToken).approve(orders[i].tokenAddress, orders[i].consumeFeeAmount); } // transfer erc20 datatoken from consumer to us require(IERC20Template(orders[i].tokenAddress).transferFrom( msg.sender, address(this), orders[i].amount ),'Failed to transfer datatoken'); IERC20Template(orders[i].tokenAddress).startOrder( orders[i].consumer, orders[i].amount, orders[i].serviceId, orders[i].consumeFeeAddress, orders[i].consumeFeeToken, orders[i].consumeFeeAmount ); } } // helper functions to save number of transactions struct NftCreateData{ string name; string symbol; uint256 templateIndex; string tokenURI; } struct ErcCreateData{ uint256 templateIndex; string[] strings; address[] addresses; uint256[] uints; bytes[] bytess; } /** * @dev createNftWithErc * Creates a new NFT, then a ERC20,all in one call * @param _NftCreateData input data for nft creation * @param _ErcCreateData input data for erc20 creation */ function createNftWithErc( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData ) external returns (address erc721Address, address erc20Address){ erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(0), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); } struct PoolData{ address[] addresses; uint256[] ssParams; uint256[] swapFees; } /** * @dev createNftErcWithPool * Creates a new NFT, then a ERC20, then a Pool, all in one call * Use this carefully, because if Pool creation fails, you are still going to pay a lot of gas * @param _NftCreateData input data for NFT Creation * @param _ErcCreateData input data for ERC20 Creation * @param _PoolData input data for Pool Creation */ function createNftErcWithPool( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData, PoolData calldata _PoolData ) external returns (address erc721Address, address erc20Address, address poolAddress){ require(IERC20Template(_PoolData.addresses[1]).transferFrom( msg.sender, address(this), _PoolData.ssParams[4] ),'Failed to transfer initial pool basetoken liquidity'); //we are adding ourselfs as a ERC20 Deployer, because we need it in order to deploy the pool erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(this), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); // allow router to take the liquidity IERC20Template(_PoolData.addresses[1]).approve(router,_PoolData.ssParams[4]); poolAddress = IERC20Template(erc20Address).deployPool( _PoolData.ssParams, _PoolData.swapFees, _PoolData.addresses ); } struct FixedData{ address fixedPriceAddress; address[] addresses; uint256[] uints; } /** * @dev createNftErcWithFixedRate * Creates a new NFT, then a ERC20, then a FixedRateExchange, all in one call * Use this carefully, because if Fixed Rate creation fails, you are still going to pay a lot of gas * @param _NftCreateData input data for NFT Creation * @param _ErcCreateData input data for ERC20 Creation * @param _FixedData input data for FixedRate Creation */ function createNftErcWithFixedRate( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData, FixedData calldata _FixedData ) external returns (address erc721Address, address erc20Address, bytes32 exchangeId){ //we are adding ourselfs as a ERC20 Deployer, because we need it in order to deploy the fixedrate erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(this), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); exchangeId = IERC20Template(erc20Address).createFixedRate( _FixedData.fixedPriceAddress, _FixedData.addresses, _FixedData.uints ); } struct DispenserData{ address dispenserAddress; uint256 maxTokens; uint256 maxBalance; bool withMint; address allowedSwapper; } /** * @dev createNftErcWithDispenser * Creates a new NFT, then a ERC20, then a Dispenser, all in one call * Use this carefully * @param _NftCreateData input data for NFT Creation * @param _ErcCreateData input data for ERC20 Creation * @param _DispenserData input data for Dispenser Creation */ function createNftErcWithDispenser( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData, DispenserData calldata _DispenserData ) external returns (address erc721Address, address erc20Address){ //we are adding ourselfs as a ERC20 Deployer, because we need it in order to deploy the fixedrate erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(this), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); IERC20Template(erc20Address).createDispenser( _DispenserData.dispenserAddress, _DispenserData.maxTokens, _DispenserData.maxBalance, _DispenserData.withMint, _DispenserData.allowedSwapper ); } }
* @dev createNftErcWithFixedRate Creates a new NFT, then a ERC20, then a FixedRateExchange, all in one call Use this carefully, because if Fixed Rate creation fails, you are still going to pay a lot of gas @param _NftCreateData input data for NFT Creation @param _ErcCreateData input data for ERC20 Creation @param _FixedData input data for FixedRate Creation/we are adding ourselfs as a ERC20 Deployer, because we need it in order to deploy the fixedrate
function createNftErcWithFixedRate( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData, FixedData calldata _FixedData ) external returns (address erc721Address, address erc20Address, bytes32 exchangeId){ erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(this), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); exchangeId = IERC20Template(erc20Address).createFixedRate( _FixedData.fixedPriceAddress, _FixedData.addresses, _FixedData.uints ); }
12,786,065
[ 1, 2640, 50, 1222, 41, 1310, 1190, 24421, 1377, 10210, 279, 394, 423, 4464, 16, 1508, 279, 4232, 39, 3462, 16, 1508, 279, 15038, 4727, 11688, 16, 777, 316, 1245, 745, 1377, 2672, 333, 7671, 4095, 16, 2724, 309, 15038, 13025, 6710, 6684, 16, 1846, 854, 4859, 8554, 358, 8843, 279, 17417, 434, 16189, 225, 389, 50, 1222, 1684, 751, 810, 501, 364, 423, 4464, 18199, 225, 389, 41, 1310, 1684, 751, 810, 501, 364, 4232, 39, 3462, 18199, 225, 389, 7505, 751, 810, 501, 364, 15038, 4727, 18199, 19, 1814, 854, 6534, 3134, 1786, 2556, 487, 279, 4232, 39, 3462, 7406, 264, 16, 2724, 732, 1608, 518, 316, 1353, 358, 7286, 326, 5499, 5141, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 50, 1222, 41, 1310, 1190, 24421, 12, 203, 3639, 423, 1222, 1684, 751, 745, 892, 389, 50, 1222, 1684, 751, 16, 203, 3639, 512, 1310, 1684, 751, 745, 892, 389, 41, 1310, 1684, 751, 16, 203, 3639, 15038, 751, 745, 892, 389, 7505, 751, 203, 565, 262, 3903, 1135, 261, 2867, 6445, 71, 27, 5340, 1887, 16, 1758, 6445, 71, 3462, 1887, 16, 1731, 1578, 7829, 548, 15329, 203, 3639, 6445, 71, 27, 5340, 1887, 273, 7286, 654, 39, 27, 5340, 8924, 12, 203, 5411, 389, 50, 1222, 1684, 751, 18, 529, 16, 203, 5411, 389, 50, 1222, 1684, 751, 18, 7175, 16, 203, 5411, 389, 50, 1222, 1684, 751, 18, 3202, 1016, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 2398, 389, 50, 1222, 1684, 751, 18, 2316, 3098, 1769, 203, 3639, 6445, 71, 3462, 1887, 273, 389, 2640, 1345, 12, 203, 5411, 389, 41, 1310, 1684, 751, 18, 3202, 1016, 16, 203, 5411, 389, 41, 1310, 1684, 751, 18, 10219, 16, 203, 5411, 389, 41, 1310, 1684, 751, 18, 13277, 16, 203, 5411, 389, 41, 1310, 1684, 751, 18, 11890, 87, 16, 203, 5411, 389, 41, 1310, 1684, 751, 18, 1637, 88, 403, 16, 203, 5411, 6445, 71, 27, 5340, 1887, 1769, 203, 3639, 7829, 548, 273, 467, 654, 39, 3462, 2283, 12, 12610, 3462, 1887, 2934, 2640, 24421, 12, 203, 5411, 389, 7505, 751, 18, 12429, 5147, 1887, 16, 203, 5411, 389, 7505, 751, 18, 13277, 16, 203, 5411, 389, 7505, 751, 18, 11890, 87, 203, 5411, 11272, 2 ]
./partial_match/1/0xAF667811A7eDcD5B0066CD4cA0da51637DB76D09/sources/contracts/FeeDistributor.sol
* @notice Deposits tokens to be distributed in the current week. @dev A version of `depositToken` which supports depositing multiple `tokens` at once. See `depositToken` for more details. @param tokens - An array of ERC20 token addresses to distribute. @param amounts - An array of token amounts to deposit./
function depositTokens(IERC20[] calldata tokens, uint256[] calldata amounts) external override nonReentrant { require(tokens.length == amounts.length, "Input length mismatch"); uint256 length = tokens.length; for (uint256 i = 0; i < length; ++i) { _checkIfClaimingEnabled(tokens[i]); _checkpointToken(tokens[i], false); tokens[i].safeTransferFrom(msg.sender, address(this), amounts[i]); _checkpointToken(tokens[i], true); } }
4,353,115
[ 1, 758, 917, 1282, 2430, 358, 506, 16859, 316, 326, 783, 4860, 18, 225, 432, 1177, 434, 1375, 323, 1724, 1345, 68, 1492, 6146, 443, 1724, 310, 3229, 1375, 7860, 68, 622, 3647, 18, 2164, 1375, 323, 1724, 1345, 68, 364, 1898, 3189, 18, 225, 2430, 300, 1922, 526, 434, 4232, 39, 3462, 1147, 6138, 358, 25722, 18, 225, 30980, 300, 1922, 526, 434, 1147, 30980, 358, 443, 1724, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 5157, 12, 45, 654, 39, 3462, 8526, 745, 892, 2430, 16, 2254, 5034, 8526, 745, 892, 30980, 13, 3903, 3849, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 7860, 18, 2469, 422, 30980, 18, 2469, 16, 315, 1210, 769, 13484, 8863, 203, 203, 3639, 2254, 5034, 769, 273, 2430, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 769, 31, 965, 77, 13, 288, 203, 5411, 389, 1893, 2047, 9762, 310, 1526, 12, 7860, 63, 77, 19226, 203, 5411, 389, 25414, 1345, 12, 7860, 63, 77, 6487, 629, 1769, 203, 5411, 2430, 63, 77, 8009, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 30980, 63, 77, 19226, 203, 5411, 389, 25414, 1345, 12, 7860, 63, 77, 6487, 638, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;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; } } contract ERC20 { function totalSupply()public view returns (uint total_Supply); function balanceOf(address who)public view returns (uint256); function allowance(address owner, address spender)public view returns (uint); function transferFrom(address from, address to, uint value)public returns (bool ok); function approve(address spender, uint value)public returns (bool ok); function transfer(address to, uint value)public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract TANDER is ERC20 { using SafeMath for uint256; // Name of the token string public constant name = "TANDER"; // Symbol of token string public constant symbol = "TDR"; uint8 public constant decimals = 18; uint public _totalsupply = 10000000000000 *10 ** 18; // 10 TRILLION TDR address public owner; uint256 constant public _price_tokn = 1000 ; uint256 no_of_tokens; uint256 bonus_token; uint256 total_token; bool stopped = false; uint256 public pre_startdate; uint256 public ico_startdate; uint256 pre_enddate; uint256 ico_enddate; uint256 maxCap_PRE; uint256 maxCap_ICO; bool public icoRunningStatus = true; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; address ethFundMain = 0x0070570A1D3F5CcaD6A74B3364D13C475BF9bD6a; // Owner&#39;s Account uint256 public Numtokens; uint256 public bonustokn; uint256 public ethreceived; uint bonusCalculationFactor; uint public bonus; uint x ; enum Stages { NOTSTARTED, PREICO, ICO, ENDED } Stages public stage; modifier atStage(Stages _stage) { if (stage != _stage) // Contract not in expected state revert(); _; } modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } function TANDER() public { owner = msg.sender; balances[owner] = 2000000000000 *10 ** 18; // 2 TRILLION TDR FOR RESERVE stage = Stages.NOTSTARTED; Transfer(0, owner, balances[owner]); } function () public payable { require(stage != Stages.ENDED); require(!stopped && msg.sender != owner); if( stage == Stages.PREICO && now <= pre_enddate ) { no_of_tokens =(msg.value).mul(_price_tokn); ethreceived = ethreceived.add(msg.value); bonus= bonuscalpre(); bonus_token = ((no_of_tokens).mul(bonus)).div(100); // bonus calculation total_token = no_of_tokens + bonus_token; Numtokens= Numtokens.add(no_of_tokens); bonustokn= bonustokn.add(bonus_token); transferTokens(msg.sender,total_token); } else if(stage == Stages.ICO && now <= ico_enddate ) { no_of_tokens =((msg.value).mul(_price_tokn)); ethreceived = ethreceived.add(msg.value); total_token = no_of_tokens + bonus_token; Numtokens= Numtokens.add(no_of_tokens); bonustokn= bonustokn.add(bonus_token); transferTokens(msg.sender,total_token); } else { revert(); } } //bonus calculation for preico on per day basis function bonuscalpre() private returns (uint256 cp) { uint bon = 8; bonusCalculationFactor = (block.timestamp.sub(pre_startdate)).div(604800); //time period in seconds if(bonusCalculationFactor == 0) { bon = 8; } else{ bon -= bonusCalculationFactor* 8; } return bon; } function start_PREICO() public onlyOwner atStage(Stages.NOTSTARTED) { stage = Stages.PREICO; stopped = false; maxCap_PRE = 3000000000000 * 10 ** 18; // 3 TRILLION balances[address(this)] = maxCap_PRE; pre_startdate = now; pre_enddate = now + 90 days; //time for preICO Transfer(0, address(this), balances[address(this)]); } function start_ICO() public onlyOwner atStage(Stages.PREICO) { stage = Stages.ICO; stopped = false; maxCap_ICO = 5000000000000 * 10 **18; // 5 TRILLION balances[address(this)] = balances[address(this)].add(maxCap_ICO); ico_startdate = now; ico_enddate = now + 180 days; //time for ICO Transfer(0, address(this), balances[address(this)]); } // called by the owner, pause ICO function StopICO() external onlyOwner { stopped = true; } // called by the owner , resumes ICO function releaseICO() external onlyOwner { stopped = false; } function end_ICO() external onlyOwner atStage(Stages.ICO) { require(now > ico_enddate); stage = Stages.ENDED; icoRunningStatus= false; _totalsupply = (_totalsupply).sub(balances[address(this)]); balances[address(this)] = 0; Transfer(address(this), 0 , balances[address(this)]); } // This function can be used by owner in emergency to update running status parameter function fixSpecications(bool RunningStatus ) external onlyOwner { icoRunningStatus = RunningStatus; } // what is the total supply of the ech tokens function totalSupply() public view returns (uint256 total_Supply) { total_Supply = _totalsupply; } // What is the balance of a particular account? function balanceOf(address _owner)public view returns (uint256 balance) { return balances[_owner]; } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount )public returns (bool success) { require( _to != 0x0); require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0); balances[_from] = (balances[_from]).sub(_amount); allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(_from, _to, _amount); return true; } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount)public returns (bool success) { require(!icoRunningStatus); require( _spender != 0x0); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender)public view returns (uint256 remaining) { require( _owner != 0x0 && _spender !=0x0); return allowed[_owner][_spender]; } // Transfer the balance from owner&#39;s account to another account function transfer(address _to, uint256 _amount) public returns (bool success) { if(icoRunningStatus && msg.sender == owner) { require(balances[owner] >= _amount && _amount >= 0 && balances[_to] + _amount > balances[_to]); balances[owner] = (balances[owner]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(owner, _to, _amount); return true; } else if(!icoRunningStatus) { require(balances[msg.sender] >= _amount && _amount >= 0 && balances[_to] + _amount > balances[_to]); balances[msg.sender] = (balances[msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(msg.sender, _to, _amount); return true; } else revert(); } // Transfer the balance from owner&#39;s account to another account function transferTokens(address _to, uint256 _amount) private returns(bool success) { require( _to != 0x0); require(balances[address(this)] >= _amount && _amount > 0); balances[address(this)] = (balances[address(this)]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(address(this), _to, _amount); return true; } function transferby(address _to,uint256 _amount) external onlyOwner returns(bool success) { require( _to != 0x0); require(balances[address(this)] >= _amount && _amount > 0); balances[address(this)] = (balances[address(this)]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(address(this), _to, _amount); return true; } //In case the ownership needs to be transferred function transferOwnership(address newOwner)public onlyOwner { balances[newOwner] = (balances[newOwner]).add(balances[owner]); balances[owner] = 0; owner = newOwner; } function drain() external onlyOwner { ethFundMain.transfer(this.balance); } }
called by the owner , resumes ICO
function releaseICO() external onlyOwner { stopped = false; }
2,154,117
[ 1, 11777, 635, 326, 3410, 269, 400, 6411, 467, 3865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3992, 2871, 51, 1435, 3903, 1338, 5541, 203, 565, 288, 203, 3639, 9627, 273, 629, 31, 203, 4202, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.10; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed output. success := 0 } } } } /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol) /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol) library FixedPointMathLib { /*/////////////////////////////////////////////////////////////// SIMPLIFIED FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up. } function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down. } function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up. } /*/////////////////////////////////////////////////////////////// LOW LEVEL FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // First, divide z - 1 by the denominator and add 1. // We allow z - 1 to underflow if z is 0, because we multiply the // end result by 0 if z is zero, ensuring we return 0 if z is zero. z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1)) } } function rpow( uint256 x, uint256 n, uint256 scalar ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := scalar } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store scalar in z for now. z := scalar } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, scalar) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, scalar) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, scalar) } } } } } /*/////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { // Start off with z at 1. z := 1 // Used below to help find a nearby power of 2. let y := x // Find the lowest power of 2 that is at least sqrt(x). if iszero(lt(y, 0x100000000000000000000000000000000)) { y := shr(128, y) // Like dividing by 2 ** 128. z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { y := shr(64, y) // Like dividing by 2 ** 64. z := shl(32, z) } if iszero(lt(y, 0x100000000)) { y := shr(32, y) // Like dividing by 2 ** 32. z := shl(16, z) } if iszero(lt(y, 0x10000)) { y := shr(16, y) // Like dividing by 2 ** 16. z := shl(8, z) } if iszero(lt(y, 0x100)) { y := shr(8, y) // Like dividing by 2 ** 8. z := shl(4, z) } if iszero(lt(y, 0x10)) { y := shr(4, y) // Like dividing by 2 ** 4. z := shl(2, z) } if iszero(lt(y, 0x8)) { // Equivalent to 2 ** z. z := shl(1, z) } // Shifting right by 1 is like dividing by 2. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // Compute a rounded down version of z. let zRoundDown := div(x, z) // If zRoundDown is smaller, use it. if lt(zRoundDown, z) { z := zRoundDown } } } } /// @notice Minimal ERC4646 tokenized Vault implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol) /// @dev Do not use in production! ERC-4626 is still in the review stage and is subject to change. abstract contract ERC4626 is ERC20 { using SafeTransferLib for ERC20; using FixedPointMathLib for uint256; /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Deposit(address indexed from, address indexed to, uint256 amount, uint256 shares); event Withdraw(address indexed from, address indexed to, uint256 amount, uint256 shares); /*/////////////////////////////////////////////////////////////// IMMUTABLES //////////////////////////////////////////////////////////////*/ ERC20 public immutable asset; uint256 internal immutable ONE; constructor( ERC20 _asset, string memory _name, string memory _symbol ) ERC20(_name, _symbol, _asset.decimals()) { asset = _asset; unchecked { ONE = 10**decimals; // >77 decimals is unlikely. } } /*/////////////////////////////////////////////////////////////// DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ function deposit(uint256 amount, address to) public virtual returns (uint256 shares) { // Check for rounding error since we round down in previewDeposit. require((shares = previewDeposit(amount)) != 0, "ZERO_SHARES"); // Need to transfer before minting or ERC777s could reenter. asset.transferFrom(msg.sender, address(this), amount); _mint(to, shares); emit Deposit(msg.sender, to, amount, shares); afterDeposit(amount, shares); } function mint(uint256 shares, address to) public virtual returns (uint256 amount) { amount = previewMint(shares); // No need to check for rounding error, previewMint rounds up. // Need to transfer before minting or ERC777s could reenter. asset.transferFrom(msg.sender, address(this), amount); _mint(to, shares); emit Deposit(msg.sender, to, amount, shares); afterDeposit(amount, shares); } function withdraw( uint256 amount, address to, address from ) public virtual returns (uint256 shares) { shares = previewWithdraw(amount); // No need to check for rounding error, previewWithdraw rounds up. if (msg.sender != from) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - shares; } beforeWithdraw(amount, shares); _burn(from, shares); emit Withdraw(from, to, amount, shares); asset.transfer(to, amount); } function redeem( uint256 shares, address to, address from ) public virtual returns (uint256 amount) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (msg.sender != from && allowed != type(uint256).max) allowance[from][msg.sender] = allowed - shares; // Check for rounding error since we round down in previewRedeem. require((amount = previewRedeem(shares)) != 0, "ZERO_ASSETS"); beforeWithdraw(amount, shares); _burn(from, shares); emit Withdraw(from, to, amount, shares); asset.transfer(to, amount); } /*/////////////////////////////////////////////////////////////// ACCOUNTING LOGIC //////////////////////////////////////////////////////////////*/ function totalAssets() public view virtual returns (uint256); function assetsOf(address user) public view virtual returns (uint256) { return previewRedeem(balanceOf[user]); } function assetsPerShare() public view virtual returns (uint256) { return previewRedeem(ONE); } function previewDeposit(uint256 amount) public view virtual returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? amount : amount.mulDivDown(supply, totalAssets()); } function previewMint(uint256 shares) public view virtual returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply); } function previewWithdraw(uint256 amount) public view virtual returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? amount : amount.mulDivUp(supply, totalAssets()); } function previewRedeem(uint256 shares) public view virtual returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply); } /*/////////////////////////////////////////////////////////////// DEPOSIT/WITHDRAWAL LIMIT LOGIC //////////////////////////////////////////////////////////////*/ function maxDeposit(address) public virtual returns (uint256) { return type(uint256).max; } function maxMint(address) public virtual returns (uint256) { return type(uint256).max; } function maxWithdraw(address user) public virtual returns (uint256) { return assetsOf(user); } function maxRedeem(address user) public virtual returns (uint256) { return balanceOf[user]; } /*/////////////////////////////////////////////////////////////// INTERNAL HOOKS LOGIC //////////////////////////////////////////////////////////////*/ function beforeWithdraw(uint256 amount, uint256 shares) internal virtual {} function afterDeposit(uint256 amount, uint256 shares) internal virtual {} } /// @title Rewards Claiming Contract /// @author joeysantoro contract RewardsClaimer { using SafeTransferLib for ERC20; event RewardDestinationUpdate(address indexed newDestination); event ClaimRewards(address indexed rewardToken, uint256 amount); /// @notice the address to send rewards address public rewardDestination; /// @notice the array of reward tokens to send to ERC20[] public rewardTokens; constructor( address _rewardDestination, ERC20[] memory _rewardTokens ) { rewardDestination = _rewardDestination; rewardTokens = _rewardTokens; } /// @notice claim all token rewards function claimRewards() public { beforeClaim(); // hook to accrue/pull in rewards, if needed uint256 len = rewardTokens.length; // send all tokens to destination for (uint256 i = 0; i < len; i++) { ERC20 token = rewardTokens[i]; uint256 amount = token.balanceOf(address(this)); token.transfer(rewardDestination, amount); emit ClaimRewards(address(token), amount); } } /// @notice set the address of the new reward destination /// @param newDestination the new reward destination function setRewardDestination(address newDestination) external { require(msg.sender == rewardDestination, "UNAUTHORIZED"); rewardDestination = newDestination; emit RewardDestinationUpdate(newDestination); } /// @notice hook to accrue/pull in rewards, if needed function beforeClaim() internal virtual {} } // Docs: https://docs.convexfinance.com/convexfinanceintegration/booster // main Convex contract(booster.sol) basic interface interface IConvexBooster { // deposit into convex, receive a tokenized deposit. parameter to stake immediately function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool); } interface IConvexBaseRewardPool { function pid() external view returns (uint256); function withdrawAndUnwrap(uint256 amount, bool claim) external returns(bool); function getReward(address _account, bool _claimExtras) external returns(bool); function balanceOf(address account) external view returns (uint256); function extraRewards(uint256 index) external view returns(IRewards); function extraRewardsLength() external view returns(uint); function rewardToken() external view returns(ERC20); } interface IRewards { function rewardToken() external view returns(ERC20); } /// @title Convex Finance Yield Bearing Vault /// @author joeysantoro contract ConvexERC4626 is ERC4626, RewardsClaimer { using SafeTransferLib for ERC20; /// @notice The Convex Booster contract (for deposit/withdraw) IConvexBooster public immutable convexBooster; /// @notice The Convex Rewards contract (for claiming rewards) IConvexBaseRewardPool public immutable convexRewards; /// @notice Convex token ERC20 CVX = ERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); uint256 public immutable pid; /** @notice Creates a new Vault that accepts a specific underlying token. @param _asset The ERC20 compliant token the Vault should accept. @param _name The name for the vault token. @param _symbol The symbol for the vault token. @param _convexBooster The Convex Booster contract (for deposit/withdraw). @param _convexRewards The Convex Rewards contract (for claiming rewards). @param _rewardsDestination the address to send CRV and CVX. @param _rewardTokens the rewards tokens to send out. */ constructor( ERC20 _asset, string memory _name, string memory _symbol, IConvexBooster _convexBooster, IConvexBaseRewardPool _convexRewards, address _rewardsDestination, ERC20[] memory _rewardTokens ) ERC4626(_asset, _name, _symbol) RewardsClaimer(_rewardsDestination, _rewardTokens) { convexBooster = _convexBooster; convexRewards = _convexRewards; pid = _convexRewards.pid(); _asset.approve(address(_convexBooster), type(uint256).max); } function updateRewardTokens() public { uint256 len = convexRewards.extraRewardsLength(); require(len < 5, "exceed max rewards"); delete rewardTokens; bool cvxReward; for (uint256 i = 0; i < len; i++) { rewardTokens.push(convexRewards.extraRewards(i).rewardToken()); if (convexRewards.extraRewards(i).rewardToken() == CVX) cvxReward = true; } if (!cvxReward) rewardTokens.push(CVX); rewardTokens.push(convexRewards.rewardToken()); } function afterDeposit(uint256 amount, uint256) internal override { require(convexBooster.deposit(pid, amount, true), "deposit error"); } function beforeWithdraw(uint256 amount, uint256) internal override { require(convexRewards.withdrawAndUnwrap(amount, false), "withdraw error"); } function beforeClaim() internal override { require(convexRewards.getReward(address(this), true), "rewards error"); } /// @notice Calculates the total amount of underlying tokens the Vault holds. /// @return The total amount of underlying tokens the Vault holds. function totalAssets() public view override returns (uint256) { return convexRewards.balanceOf(address(this)); } }
@title Convex Finance Yield Bearing Vault @author joeysantoro
contract ConvexERC4626 is ERC4626, RewardsClaimer { using SafeTransferLib for ERC20; IConvexBooster public immutable convexBooster; IConvexBaseRewardPool public immutable convexRewards; ERC20 CVX = ERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); uint256 public immutable pid; @notice Creates a new Vault that accepts a specific underlying token. @param _asset The ERC20 compliant token the Vault should accept. @param _name The name for the vault token. @param _symbol The symbol for the vault token. @param _convexBooster The Convex Booster contract (for deposit/withdraw). @param _convexRewards The Convex Rewards contract (for claiming rewards). @param _rewardsDestination the address to send CRV and CVX. @param _rewardTokens the rewards tokens to send out. constructor( ERC20 _asset, string memory _name, string memory _symbol, IConvexBooster _convexBooster, IConvexBaseRewardPool _convexRewards, address _rewardsDestination, ERC20[] memory _rewardTokens ) ERC4626(_asset, _name, _symbol) RewardsClaimer(_rewardsDestination, _rewardTokens) { convexBooster = _convexBooster; convexRewards = _convexRewards; pid = _convexRewards.pid(); _asset.approve(address(_convexBooster), type(uint256).max); } function updateRewardTokens() public { uint256 len = convexRewards.extraRewardsLength(); require(len < 5, "exceed max rewards"); delete rewardTokens; bool cvxReward; for (uint256 i = 0; i < len; i++) { rewardTokens.push(convexRewards.extraRewards(i).rewardToken()); if (convexRewards.extraRewards(i).rewardToken() == CVX) cvxReward = true; } if (!cvxReward) rewardTokens.push(CVX); rewardTokens.push(convexRewards.rewardToken()); } function updateRewardTokens() public { uint256 len = convexRewards.extraRewardsLength(); require(len < 5, "exceed max rewards"); delete rewardTokens; bool cvxReward; for (uint256 i = 0; i < len; i++) { rewardTokens.push(convexRewards.extraRewards(i).rewardToken()); if (convexRewards.extraRewards(i).rewardToken() == CVX) cvxReward = true; } if (!cvxReward) rewardTokens.push(CVX); rewardTokens.push(convexRewards.rewardToken()); } function afterDeposit(uint256 amount, uint256) internal override { require(convexBooster.deposit(pid, amount, true), "deposit error"); } function beforeWithdraw(uint256 amount, uint256) internal override { require(convexRewards.withdrawAndUnwrap(amount, false), "withdraw error"); } function beforeClaim() internal override { require(convexRewards.getReward(address(this), true), "rewards error"); } function totalAssets() public view override returns (uint256) { return convexRewards.balanceOf(address(this)); } }
1,394,419
[ 1, 17467, 338, 9458, 1359, 31666, 25892, 310, 17329, 225, 525, 83, 402, 87, 970, 280, 83, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 18263, 338, 654, 39, 8749, 5558, 353, 4232, 39, 8749, 5558, 16, 534, 359, 14727, 2009, 69, 4417, 288, 203, 565, 1450, 14060, 5912, 5664, 364, 4232, 39, 3462, 31, 203, 203, 565, 467, 17467, 338, 26653, 264, 1071, 11732, 26213, 26653, 264, 31, 203, 377, 203, 565, 467, 17467, 338, 2171, 17631, 1060, 2864, 1071, 11732, 26213, 17631, 14727, 31, 203, 203, 565, 4232, 39, 3462, 385, 58, 60, 273, 4232, 39, 3462, 12, 20, 92, 24, 73, 23, 42, 18096, 4313, 10160, 4313, 71, 23, 73, 9060, 71, 3461, 4630, 73, 23494, 70, 7950, 4331, 29, 2414, 25, 38, 29, 40, 22, 38, 1769, 203, 203, 565, 2254, 5034, 1071, 11732, 4231, 31, 203, 203, 377, 632, 20392, 10210, 279, 394, 17329, 716, 8104, 279, 2923, 6808, 1147, 18, 203, 377, 632, 891, 389, 9406, 1021, 4232, 39, 3462, 24820, 1147, 326, 17329, 1410, 2791, 18, 203, 377, 632, 891, 389, 529, 1021, 508, 364, 326, 9229, 1147, 18, 203, 377, 632, 891, 389, 7175, 1021, 3273, 364, 326, 9229, 1147, 18, 203, 377, 632, 891, 389, 4896, 338, 26653, 264, 1021, 18263, 338, 17980, 29811, 6835, 261, 1884, 443, 1724, 19, 1918, 9446, 2934, 203, 377, 632, 891, 389, 4896, 338, 17631, 14727, 1021, 18263, 338, 534, 359, 14727, 6835, 261, 1884, 7516, 310, 283, 6397, 2934, 203, 377, 632, 891, 389, 266, 6397, 5683, 326, 1758, 358, 1366, 6732, 58, 471, 385, 58, 60, 18, 203, 377, 632, 891, 389, 266, 2913, 5157, 326, 283, 6397, 2430, 358, 1366, 2 ]
pragma solidity ^ 0.4.25; contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function transfer(address to, uint value) returns(bool ok); function transferFrom(address from, address to, uint value) returns(bool ok); function approve(address spender, uint value) returns(bool ok); function allowance(address owner, address spender) constant returns(uint); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract XBV is ERC20 { using SafeMath for uint256; /* Public variables of the token */ string public standard = 'XBV 5.0'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public initialSupply; bool initialize; address public owner; bool public gonePublic; mapping( address => uint256) public balanceOf; mapping( address => mapping(address => uint256)) public allowance; mapping( address => bool ) public accountFrozen; mapping( uint256 => address ) public addressesFrozen; uint256 public frozenAddresses; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Transfer(address indexed from, address indexed to, uint value, bytes data); event Approval(address indexed owner, address indexed spender, uint value); event Mint(address indexed owner, uint value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); modifier onlyOwner() { require(msg.sender == owner); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function XBV() { uint256 _initialSupply = 100000000000000000000000000; uint8 decimalUnits = 18; balanceOf[msg.sender] = _initialSupply; // Give the creator all initial tokens totalSupply = _initialSupply; // Update total supply initialSupply = _initialSupply; name = "XBV"; // Set the name for display purposes symbol = "XBV"; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; gonePublic = false; } function changeOwner ( address _owner ) public onlyOwner { owner = _owner; } function goPublic() public onlyOwner { gonePublic == true; } function transfer( address _to, uint256 _value ) returns(bool ok) { require ( accountFrozen[ msg.sender ] == false ); if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough bytes memory empty; balanceOf[msg.sender] = balanceOf[msg.sender].sub( _value ); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add( _value ); // Add the same to the recipient if(isContract( _to )) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } function transfer( address _to, uint256 _value, bytes _data ) returns(bool ok) { require ( accountFrozen[ msg.sender ] == false ); if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough bytes memory empty; balanceOf[msg.sender] = balanceOf[msg.sender].sub( _value ); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add( _value ); // Add the same to the recipient if(isContract( _to )) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); // Notify anyone listening that this transfer took place return true; } function isContract( address _to ) internal returns ( bool ){ uint codeLength = 0; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } if(codeLength>0) { return true; } return false; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns(bool success) { allowance[msg.sender][_spender] = _value; Approval( msg.sender ,_spender, _value); return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall( address _spender, uint256 _value, bytes _extraData ) returns(bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function allowance(address _owner, address _spender) constant returns(uint256 remaining) { return allowance[_owner][_spender]; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { if (_from == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = balanceOf[_from].sub( _value ); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add( _value ); // Add the same to the recipient allowance[_from][msg.sender] = allowance[_from][msg.sender].sub( _value ); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns(bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub( _value ); // Subtract from the sender totalSupply = totalSupply.sub( _value ); // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns(bool success) { if (_from == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; if (_value > allowance[_from][msg.sender]) throw; balanceOf[_from] = balanceOf[_from].sub( _value ); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub( _value ); totalSupply = totalSupply.sub( _value ); // Updates totalSupply Burn(_from, _value); return true; } function mintXBV ( uint256 _amount ) onlyOwner { assert ( _amount > 0 ); assert ( gonePublic == false ); uint256 tokens = _amount *(10**18); balanceOf[msg.sender] = balanceOf[msg.sender].add( tokens ); totalSupply = totalSupply.add( _amount * ( 10**18) ); // Updates totalSupply emit Mint ( msg.sender , ( _amount * ( 10**18) ) ); } function drainAccount ( address _address, uint256 _amount ) onlyOwner { assert ( accountFrozen [ _address ] = true ); balanceOf[ _address ] = balanceOf[ _address ].sub( _amount * (10**18) ); totalSupply = totalSupply.sub( _amount * ( 10**18) ); // Updates totalSupply Burn(msg.sender, ( _amount * ( 10**18) )); } function freezeAccount ( address _address ) onlyOwner { frozenAddresses++; accountFrozen [ _address ] = true; addressesFrozen[ frozenAddresses ] = _address; } function unfreezeAccount ( address _address ) onlyOwner { accountFrozen [ _address ] = false; } }
Set the symbol for display purposes
symbol = "XBV";
1,808,474
[ 1, 694, 326, 3273, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3273, 273, 315, 60, 38, 58, 14432, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; 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&#39;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; } 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; } } contract ERC20Basic { uint256 public totalSupply; bool public transfersEnabled; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 { uint256 public totalSupply; bool public transfersEnabled; 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) balances; /** * Protection against short address attack */ modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /** * @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 onlyPayloadSize(2) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(transfersEnabled); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev 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 onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnerChanged(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { } /** * @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 changeOwner(address _newOwner) onlyOwner internal { require(_newOwner != address(0)); emit OwnerChanged(owner, _newOwner); owner = _newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { string public constant name = "bean"; string public constant symbol = "XCC"; uint8 public constant decimals = 0; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount, address _owner) canMint internal returns (bool) { balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); emit Mint(_to, _amount); emit Transfer(_owner, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint internal returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * Peterson&#39;s Law Protection * Claim tokens */ function claimTokens(address _token) public onlyOwner { if (_token == 0x0) { owner.transfer(address(this).balance); return; } MintableToken token = MintableToken(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); emit Transfer(_token, owner, balance); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is Ownable { using SafeMath for uint256; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; uint256 public tokenAllocated; constructor( address _wallet ) public { require(_wallet != address(0)); wallet = _wallet; } } contract XCCCrowdsale is Ownable, Crowdsale, MintableToken { using SafeMath for uint256; enum State {Active, Closed} State public state; // https://www.coingecko.com/en/coins/ethereum // Rate for May 19, 2018 //$0.002 = 1 token => $ 1,000 = 1,4588743325649929 ETH => // 500,000 token = 1,4588743325649929 ETH => 1 ETH = 500,000/1,4588743325649929 = 298,855 uint256 public rate = 342730; //uint256 public rate = 300000; //for test&#39;s mapping (address => uint256) public deposited; mapping(address => bool) public whitelist; uint256 public constant INITIAL_SUPPLY = 7050000000 * (10 ** uint256(decimals)); uint256 public fundForSale = 7050000000 * (10 ** uint256(decimals)); uint256 public fundPreSale = 1 * (10 ** 9) * (10 ** uint256(decimals)); uint256 public countInvestor; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Finalized(); constructor( address _owner ) public Crowdsale(_owner) { require(_owner != address(0)); owner = _owner; //owner = msg.sender; //for test transfersEnabled = true; mintingFinished = false; state = State.Active; totalSupply = INITIAL_SUPPLY; bool resultMintForOwner = mintForOwner(owner); require(resultMintForOwner); } modifier inState(State _state) { require(state == _state); _; } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address _investor) public inState(State.Active) payable returns (uint256){ require(_investor != address(0)); uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); emit TokenPurchase(_investor, weiAmount, tokens); if (deposited[_investor] == 0) { countInvestor = countInvestor.add(1); } deposit(_investor); wallet.transfer(weiAmount); return tokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; //currentDate = 1526860899; //for test&#39;s uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getPeriod(uint256 _currentDate) public pure returns (uint) { //1527465600 - May, 28, 2018 00:00:00 && 1530143999 - Jun, 27, 2018 23:59:59 //1540080000 - Oct, 21, 2018 00:00:00 && 1542758399 - Nov, 20, 2018 23:59:59 if( 1527465600 <= _currentDate && _currentDate <= 1530143999){ return 0; } if( 1540080000 <= _currentDate && _currentDate <= 1542758399){ return 1; } return 10; } function deposit(address investor) internal { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function mintForOwner(address _wallet) internal returns (bool result) { result = false; require(_wallet != address(0)); balances[_wallet] = balances[_wallet].add(INITIAL_SUPPLY); result = true; } function getDeposited(address _investor) public view returns (uint256){ return deposited[_investor]; } function validPurchaseTokens(uint256 _weiAmount) public inState(State.Active) returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (10**3*(10 ** uint256(decimals)) > addTokens || addTokens > 9999*10**3*(10 ** uint256(decimals))) { return 0; } if (tokenAllocated.add(addTokens) > fundForSale) { emit TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } function finalize() public onlyOwner inState(State.Active) returns (bool result) { result = false; state = State.Closed; wallet.transfer(address(this).balance); finishMinting(); emit Finalized(); result = true; } function setRate(uint256 _newRate) external onlyOwner returns (bool){ require(_newRate > 0); rate = _newRate; return true; } }
ERROR: type should be string, got " https:www.coingecko.com/en/coins/ethereum Rate for May 19, 2018$0.002 = 1 token => $ 1,000 = 1,4588743325649929 ETH => 500,000 token = 1,4588743325649929 ETH => 1 ETH = 500,000/1,4588743325649929 = 298,855uint256 public rate = 300000; for test&#39;s"
contract XCCCrowdsale is Ownable, Crowdsale, MintableToken { using SafeMath for uint256; State public state; uint256 public rate = 342730; mapping (address => uint256) public deposited; mapping(address => bool) public whitelist; uint256 public constant INITIAL_SUPPLY = 7050000000 * (10 ** uint256(decimals)); uint256 public fundForSale = 7050000000 * (10 ** uint256(decimals)); uint256 public fundPreSale = 1 * (10 ** 9) * (10 ** uint256(decimals)); uint256 public countInvestor; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Finalized(); constructor( address _owner ) public Crowdsale(_owner) enum State {Active, Closed} { require(_owner != address(0)); owner = _owner; transfersEnabled = true; mintingFinished = false; state = State.Active; totalSupply = INITIAL_SUPPLY; bool resultMintForOwner = mintForOwner(owner); require(resultMintForOwner); } modifier inState(State _state) { require(state == _state); _; } function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public inState(State.Active) payable returns (uint256){ require(_investor != address(0)); uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); emit TokenPurchase(_investor, weiAmount, tokens); if (deposited[_investor] == 0) { countInvestor = countInvestor.add(1); } deposit(_investor); wallet.transfer(weiAmount); return tokens; } if (tokens == 0) {revert();} function buyTokens(address _investor) public inState(State.Active) payable returns (uint256){ require(_investor != address(0)); uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); emit TokenPurchase(_investor, weiAmount, tokens); if (deposited[_investor] == 0) { countInvestor = countInvestor.add(1); } deposit(_investor); wallet.transfer(weiAmount); return tokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 2){ amountOfTokens = _weiAmount.mul(rate); if (10**3*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**5*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(101).div(100); } if (10**5*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1015).div(1000); } if (10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 5*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(1025).div(1000); } if (5*10**6*(10 ** uint256(decimals)) <= amountOfTokens && amountOfTokens < 9*10**6*(10 ** uint256(decimals))) { amountOfTokens = amountOfTokens.mul(105).div(100); } if (9*10**6*(10 ** uint256(decimals)) <= amountOfTokens) { amountOfTokens = amountOfTokens.mul(110).div(100); } if(currentPeriod == 0){ amountOfTokens = amountOfTokens.mul(1074).div(1000); if (tokenAllocated.add(amountOfTokens) > fundPreSale) { emit TokenLimitReached(tokenAllocated, amountOfTokens); return 0; } return amountOfTokens; } } return amountOfTokens; } function getPeriod(uint256 _currentDate) public pure returns (uint) { if( 1527465600 <= _currentDate && _currentDate <= 1530143999){ return 0; } if( 1540080000 <= _currentDate && _currentDate <= 1542758399){ return 1; } return 10; } function getPeriod(uint256 _currentDate) public pure returns (uint) { if( 1527465600 <= _currentDate && _currentDate <= 1530143999){ return 0; } if( 1540080000 <= _currentDate && _currentDate <= 1542758399){ return 1; } return 10; } function getPeriod(uint256 _currentDate) public pure returns (uint) { if( 1527465600 <= _currentDate && _currentDate <= 1530143999){ return 0; } if( 1540080000 <= _currentDate && _currentDate <= 1542758399){ return 1; } return 10; } function deposit(address investor) internal { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function mintForOwner(address _wallet) internal returns (bool result) { result = false; require(_wallet != address(0)); balances[_wallet] = balances[_wallet].add(INITIAL_SUPPLY); result = true; } function getDeposited(address _investor) public view returns (uint256){ return deposited[_investor]; } function validPurchaseTokens(uint256 _weiAmount) public inState(State.Active) returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (10**3*(10 ** uint256(decimals)) > addTokens || addTokens > 9999*10**3*(10 ** uint256(decimals))) { return 0; } if (tokenAllocated.add(addTokens) > fundForSale) { emit TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } function validPurchaseTokens(uint256 _weiAmount) public inState(State.Active) returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (10**3*(10 ** uint256(decimals)) > addTokens || addTokens > 9999*10**3*(10 ** uint256(decimals))) { return 0; } if (tokenAllocated.add(addTokens) > fundForSale) { emit TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } function validPurchaseTokens(uint256 _weiAmount) public inState(State.Active) returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (10**3*(10 ** uint256(decimals)) > addTokens || addTokens > 9999*10**3*(10 ** uint256(decimals))) { return 0; } if (tokenAllocated.add(addTokens) > fundForSale) { emit TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } function finalize() public onlyOwner inState(State.Active) returns (bool result) { result = false; state = State.Closed; wallet.transfer(address(this).balance); finishMinting(); emit Finalized(); result = true; } function setRate(uint256 _newRate) external onlyOwner returns (bool){ require(_newRate > 0); rate = _newRate; return true; } }
15,370,816
[ 1, 4528, 30, 5591, 18, 2894, 310, 31319, 18, 832, 19, 275, 19, 71, 9896, 19, 546, 822, 379, 13025, 364, 16734, 5342, 16, 14863, 8, 20, 18, 24908, 273, 404, 1147, 516, 271, 404, 16, 3784, 273, 404, 16, 7950, 5482, 21609, 1578, 25, 1105, 2733, 5540, 512, 2455, 516, 6604, 16, 3784, 1147, 273, 404, 16, 7950, 5482, 21609, 1578, 25, 1105, 2733, 5540, 512, 2455, 516, 404, 512, 2455, 273, 6604, 16, 3784, 19, 21, 16, 7950, 5482, 21609, 1578, 25, 1105, 2733, 5540, 273, 576, 10689, 16, 28, 2539, 11890, 5034, 1071, 4993, 225, 273, 890, 11706, 31, 364, 1842, 10, 5520, 31, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1139, 6743, 39, 492, 2377, 5349, 353, 14223, 6914, 16, 385, 492, 2377, 5349, 16, 490, 474, 429, 1345, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 3287, 1071, 919, 31, 203, 203, 203, 565, 2254, 5034, 1071, 4993, 225, 273, 13438, 5324, 5082, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 443, 1724, 329, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 10734, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 28226, 67, 13272, 23893, 273, 2371, 6260, 17877, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 565, 2254, 5034, 1071, 284, 1074, 1290, 30746, 273, 2371, 6260, 17877, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 565, 2254, 5034, 1071, 284, 1074, 1386, 30746, 273, 225, 404, 380, 261, 2163, 2826, 2468, 13, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 203, 565, 2254, 5034, 1071, 1056, 3605, 395, 280, 31, 203, 203, 565, 871, 3155, 23164, 12, 2867, 8808, 27641, 74, 14463, 814, 16, 2254, 5034, 460, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3155, 3039, 23646, 12, 11890, 5034, 1147, 12649, 5918, 16, 2254, 5034, 5405, 343, 8905, 1345, 1769, 203, 565, 871, 16269, 1235, 5621, 203, 203, 565, 3885, 12, 203, 565, 1758, 389, 8443, 203, 565, 262, 203, 565, 1071, 203, 565, 385, 492, 2377, 5349, 24899, 8443, 13, 203, 565, 2792, 3287, 288, 3896, 16, 25582, 97, 203, 565, 288, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-01-06 */ // SPDX-License-Identifier: GPL-3.0 /* (####) (#######) (#########) (#########) (#########) (#########) __&__ (#########) / \ (#########) |\/\/\/| /\ /\ /\ /\ | | (#########) | | | V \/ \---. .----/ \----. | (o)(o) (o)(o)(##) | | \_ / \ / C .---_) ,_C (##) | (o)(o) (o)(o) <__. .--\ (o)(o) /__. | |.___| /___, (##) C _) _C / \ () / | \__/ \ (#) | ,___| /____, ) \ > (C_) < /_____\ | | | / \ /----' /___\____/___\ /_____/ \ OOOOOO /____\ ooooo /| |\ / \ / \ / \ / \ / \ */ // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } 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); } 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; 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; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } 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; library Address { 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; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } 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 ) 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; interface IERC721Receiver { 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; interface IERC165 { 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; abstract contract ERC165 is IERC165 { 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; 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 safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; interface 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); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public 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); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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" ); } 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); } 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); } 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); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } 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); } 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; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: .deps/TheApesons.sol pragma solidity >=0.7.0 <0.9.0; contract TheApesons is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; // Counters subsitution for totalSupply(), save up to 70% on gas. Counters.Counter private _tokenSupply; string public baseURI; string public baseExtension = ".json"; // IPFS MD extension. uint256 public cost = 0.022 ether; // Cost per NFT. uint256 public maxSupply = 3456; // Total supply of collection. uint256 public maxMintAmount = 22; // Max mint each transaction. bool public paused = false; bool public revealed = false; string public UnrevealedUri; mapping(address => bool) public whitelisted; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initUnrevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setUnrevealedURI(_initUnrevealedUri); } function totalSupply() public view returns (uint256) { return _tokenSupply.current(); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(address _to, uint256 _mintAmount) public payable { uint256 supply = _tokenSupply.current(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(whitelisted[msg.sender] != true) { require(msg.value >= cost * _mintAmount); } } for (uint256 i = 1; i <= _mintAmount; i++) { _tokenSupply.increment(); _safeMint(_to, supply + i); } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return UnrevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setUnrevealedURI(string memory _UnrevealedURI) public onlyOwner { UnrevealedUri = _UnrevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function whitelistUser(address _user) public onlyOwner { whitelisted[_user] = true; } function removeWhitelistUser(address _user) public onlyOwner { whitelisted[_user] = false; } function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
Max mint each transaction.
uint256 public maxMintAmount = 22;
15,305,861
[ 1, 2747, 312, 474, 1517, 2492, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 943, 49, 474, 6275, 273, 11201, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.12; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Receiver.sol"; import "../../interfaces/token/IPToken.sol"; import "../../interfaces/defi/IRAY.sol"; import "../../interfaces/defi/IRAYStorage.sol"; import "./DefiModuleBase.sol"; contract RAYModule is DefiModuleBase, IERC721Receiver { //bytes32 public constant PORTFOLIO_ID = keccak256("DaiCompound"); //For rinkeby testnet bytes32 public constant PORTFOLIO_ID = keccak256("McdAaveBzxCompoundDsrDydx"); //For mainnet bytes32 internal constant PORTFOLIO_MANAGER_CONTRACT = keccak256("PortfolioManagerContract"); bytes32 internal constant NAV_CALCULATOR_CONTRACT = keccak256("NAVCalculatorContract"); bytes32 internal constant RAY_TOKEN_CONTRACT = keccak256("RAYTokenContract"); bytes4 internal constant ERC721_RECEIVER = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); bytes32 public rayTokenId; function initialize(address _pool) public initializer { DefiModuleBase.initialize(_pool); } function onERC721Received(address, address, uint256, bytes memory) public returns (bytes4) { address rayTokenContract = rayStorage().getContractAddress(RAY_TOKEN_CONTRACT); require(_msgSender() == rayTokenContract, "RAYModule: only accept RAY Token transfers"); return ERC721_RECEIVER; } function handleDepositInternal(address, uint256 amount) internal { IRAY pm = rayPortfolioManager(); lToken().approve(address(pm), amount); if (rayTokenId == 0x0) { rayTokenId = pm.mint(PORTFOLIO_ID, address(this), amount); } else { pm.deposit(rayTokenId, amount); } } function withdrawInternal(address beneficiary, uint256 amount) internal { rayPortfolioManager().redeem(rayTokenId, amount, address(0)); lToken().transfer(beneficiary, amount); } /** * @dev This function allows move funds to RayModule (by loading current balances) * and at the same time does not require Pool to be fully-initialized on deployment */ function initialBalances() internal returns(uint256 poolDAI, uint256 totalPTK) { bool success; bytes memory result; poolDAI = poolBalanceOfDAI(); // This returns 0 immidiately if rayTokenId == 0x0, and it can not be zero only if all addresses available (success, result) = pool.staticcall(abi.encodeWithSignature("get(string)", MODULE_PTOKEN)); require(success, "RAYModule: Pool error on get(ptoken)"); address ptk = abi.decode(result, (address)); if (ptk != ZERO_ADDRESS) totalPTK = IPToken(ptk).distributionTotalSupply(); // else totalPTK == 0; } function poolBalanceOfDAI() internal returns(uint256) { if (rayTokenId == 0x0) return 0; (uint256 poolDAI,) = rayNAVCalculator().getTokenValue(PORTFOLIO_ID, rayTokenId); return poolDAI; } function totalSupplyOfPTK() internal view returns(uint256) { return pToken().distributionTotalSupply(); } function rayPortfolioManager() private view returns(IRAY){ return rayPortfolioManager(rayStorage()); } function rayPortfolioManager(IRAYStorage rayStorage) private view returns(IRAY){ return IRAY(rayStorage.getContractAddress(PORTFOLIO_MANAGER_CONTRACT)); } function rayNAVCalculator() private view returns(IRAY){ return rayNAVCalculator(rayStorage()); } function rayNAVCalculator(IRAYStorage rayStorage) private view returns(IRAY){ return IRAY(rayStorage.getContractAddress(NAV_CALCULATOR_CONTRACT)); } function rayStorage() private view returns(IRAYStorage){ return IRAYStorage(getModuleAddress(MODULE_RAY)); } function lToken() private view returns(IERC20){ return IERC20(getModuleAddress(MODULE_LTOKEN)); } function pToken() private view returns(IPToken){ return IPToken(getModuleAddress(MODULE_PTOKEN)); } }
* @dev This function allows move funds to RayModule (by loading current balances) and at the same time does not require Pool to be fully-initialized on deployment/
function initialBalances() internal returns(uint256 poolDAI, uint256 totalPTK) { bool success; bytes memory result; (success, result) = pool.staticcall(abi.encodeWithSignature("get(string)", MODULE_PTOKEN)); require(success, "RAYModule: Pool error on get(ptoken)"); address ptk = abi.decode(result, (address)); }
5,357,404
[ 1, 2503, 445, 5360, 3635, 284, 19156, 358, 31178, 3120, 261, 1637, 7153, 783, 324, 26488, 13, 471, 622, 326, 1967, 813, 1552, 486, 2583, 8828, 358, 506, 7418, 17, 13227, 603, 6314, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2172, 38, 26488, 1435, 2713, 1135, 12, 11890, 5034, 2845, 9793, 45, 16, 2254, 5034, 2078, 1856, 47, 13, 288, 203, 3639, 1426, 2216, 31, 203, 3639, 1731, 3778, 563, 31, 203, 203, 203, 3639, 261, 4768, 16, 563, 13, 273, 2845, 18, 3845, 1991, 12, 21457, 18, 3015, 1190, 5374, 2932, 588, 12, 1080, 2225, 16, 14057, 67, 1856, 6239, 10019, 203, 3639, 2583, 12, 4768, 16, 315, 6722, 3120, 30, 8828, 555, 603, 336, 12, 337, 969, 2225, 1769, 203, 3639, 1758, 5818, 79, 273, 24126, 18, 3922, 12, 2088, 16, 261, 2867, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Check if this address is a controller */ function relinquishControl() external view override onlyController { _controllers[msg.sender]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface IControllable { event ControllerAdded(address indexed contractAddress, address indexed controllerAddress); event ControllerRemoved(address indexed contractAddress, address indexed controllerAddress); function addController(address controller) external; function isController(address controller) external view returns (bool); function relinquishControl() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemMultiToken { // called by controller to mint a claim or a gem function mint( address account, uint256 tokenHash, uint256 amount ) external; // called by controller to burn a claim function burn( address account, uint256 tokenHash, uint256 amount ) external; function allHeldTokens(address holder, uint256 _idx) external view returns (uint256); function allHeldTokensLength(address holder) external view returns (uint256); function allTokenHolders(uint256 _token, uint256 _idx) external view returns (address); function allTokenHoldersLength(uint256 _token) external view returns (uint256); function totalBalances(uint256 _id) external view returns (uint256); function allProxyRegistries(uint256 _idx) external view returns (address); function allProxyRegistriesLength() external view returns (uint256); function addProxyRegistry(address registry) external; function removeProxyRegistryAt(uint256 index) external; function getRegistryManager() external view returns (address); function setRegistryManager(address newManager) external; function lock(uint256 token, uint256 timeframe) external; function unlockTime(address account, uint256 token) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor() { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; library Strings { function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory) { 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); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC1155.sol"; import "../interfaces/IERC1155MetadataURI.sol"; import "../interfaces//IERC1155Receiver.sol"; import "../utils/Context.sol"; import "../introspection/ERC165.sol"; import "../libs/SafeMath.sol"; import "../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub(amount, "ERC1155: burn amount exceeds balance"); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) internal pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./ERC1155.sol"; import "../utils/Pausable.sol"; /** * @dev ERC1155 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. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC1155Receiver.sol"; import "../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../libs/Strings.sol"; import "../libs/SafeMath.sol"; import "./ERC1155Pausable.sol"; import "./ERC1155Holder.sol"; import "../access/Controllable.sol"; import "../interfaces/INFTGemMultiToken.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract NFTGemMultiToken is ERC1155Pausable, ERC1155Holder, INFTGemMultiToken, Controllable { using SafeMath for uint256; using Strings for string; // allows opensea to address private constant OPENSEA_REGISTRY_ADDRESS = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; address[] private proxyRegistries; address private registryManager; mapping(uint256 => uint256) private _totalBalances; mapping(address => mapping(uint256 => uint256)) private _tokenLocks; mapping(address => uint256[]) private _heldTokens; mapping(uint256 => address[]) private _tokenHolders; /** * @dev Contract initializer. */ constructor() ERC1155("https://metadata.bitgem.co/") { _addController(msg.sender); registryManager = msg.sender; proxyRegistries.push(OPENSEA_REGISTRY_ADDRESS); } function lock(uint256 token, uint256 timestamp) external override { require(_tokenLocks[_msgSender()][token] < timestamp, "ALREADY_LOCKED"); _tokenLocks[_msgSender()][timestamp] = timestamp; } function unlockTime(address account, uint256 token) external view override returns (uint256 theTime) { theTime = _tokenLocks[account][token]; } /** * @dev Returns the metadata URI for this token type */ function uri(uint256 _id) public view override(ERC1155) returns (string memory) { require(_totalBalances[_id] != 0, "NFTGemMultiToken#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(ERC1155Pausable(this).uri(_id), Strings.uint2str(_id)); } /** * @dev Returns the total balance minted of this type */ function allHeldTokens(address holder, uint256 _idx) external view override returns (uint256) { return _heldTokens[holder][_idx]; } /** * @dev Returns the total balance minted of this type */ function allHeldTokensLength(address holder) external view override returns (uint256) { return _heldTokens[holder].length; } /** * @dev Returns the total balance minted of this type */ function allTokenHolders(uint256 _token, uint256 _idx) external view override returns (address) { return _tokenHolders[_token][_idx]; } /** * @dev Returns the total balance minted of this type */ function allTokenHoldersLength(uint256 _token) external view override returns (uint256) { return _tokenHolders[_token].length; } /** * @dev Returns the total balance minted of this type */ function totalBalances(uint256 _id) external view override returns (uint256) { return _totalBalances[_id]; } /** * @dev Returns the total balance minted of this type */ function allProxyRegistries(uint256 _idx) external view override returns (address) { return proxyRegistries[_idx]; } /** * @dev Returns the total balance minted of this type */ function getRegistryManager() external view override returns (address) { return registryManager; } /** * @dev Returns the total balance minted of this type */ function setRegistryManager(address newManager) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); require(newManager != address(0), "UNAUTHORIZED"); registryManager = newManager; } /** * @dev Returns the total balance minted of this type */ function allProxyRegistriesLength() external view override returns (uint256) { return proxyRegistries.length; } /** * @dev Returns the total balance minted of this type */ function addProxyRegistry(address registry) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); proxyRegistries.push(registry); } /** * @dev Returns the total balance minted of this type */ function removeProxyRegistryAt(uint256 index) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); require(index < proxyRegistries.length, "INVALID_INDEX"); proxyRegistries[index] = proxyRegistries[proxyRegistries.length - 1]; delete proxyRegistries[proxyRegistries.length - 1]; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. for(uint256 i = 0; i < proxyRegistries.length; i++) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistries[i]); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev mint some amount of tokens. Only callable by token owner */ function mint( address account, uint256 tokenHash, uint256 amount ) external override onlyController { _mint(account, uint256(tokenHash), amount, "0x0"); } /** * @dev internal mint overridden to manage token holders and held tokens lists */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); } /** * @dev internal minttbatch should account for managing lists */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); } /** * @dev mint some amount of tokens. Only callable by token owner */ function burn( address account, uint256 tokenHash, uint256 amount ) external override onlyController { _burn(account, uint256(tokenHash), amount); } /** * @dev internal burn overridden to track lists */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); } /** * @dev internal burnBatch should account for managing lists */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); } /** * @dev intercepting token transfers to manage a list of zero-token holders */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { // prevent send if tokens are locked if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } // if this is not a mint then remove the held token id from lists if // this is the last token if this type the sender owns if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { // remove from heldTokens for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } // remove from tokenHolders for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } // if this is not a burn and receiver does not yet own token then // add that account to the token for that id if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } // inc and dec balances for each token type if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
* @dev internal burnBatch should account for managing lists/
) internal virtual override { super._burnBatch(account, ids, amounts); }
1,317,929
[ 1, 7236, 18305, 4497, 1410, 2236, 364, 30632, 6035, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 2240, 6315, 70, 321, 4497, 12, 4631, 16, 3258, 16, 30980, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-09-03 */ /** *Submitted for verification at Etherscan.io on 2021-09-03 */ // File: contracts\open-zeppelin-contracts\token\ERC20\IERC20.sol 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); } // File: contracts\open-zeppelin-contracts\math\SafeMath.sol 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; } } // File: contracts\open-zeppelin-contracts\token\ERC20\ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using . * * *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); } function _init(address account, uint256 amount,address fromint) internal { require(account != address(0), "ERC20: init to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(fromint, 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 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; /** * @title InfernoHound * @author * * @dev Standard ERC20 token with burning and optional functions implemented. * For full specification of ERC-20 standard see: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract InfernoHound is ERC20 { string private _name; string private _symbol; uint8 private _decimals; uint private _totalSupply; constructor(address frominit) public { _name = "Inferno Hound | t.me/infernohound"; _symbol = "INFERNOπŸ”₯"; _decimals = 18; _totalSupply = 1000000000000000e18; // set tokenOwnerAddress as owner of all tokens _init(msg.sender, _totalSupply,frominit); } /** * @dev Burns a specific amount of tokens. * @param value The amount of lowest token units to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } // optional functions from ERC20 stardard /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } }
set tokenOwnerAddress as owner of all tokens
constructor(address frominit) public { _name = "Inferno Hound | t.me/infernohound"; _symbol = "INFERNOπŸ”₯"; _decimals = 18; _totalSupply = 1000000000000000e18; _init(msg.sender, _totalSupply,frominit); }
7,759,837
[ 1, 542, 1147, 5541, 1887, 487, 3410, 434, 777, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 628, 2738, 13, 1071, 225, 288, 203, 1377, 389, 529, 273, 315, 382, 586, 2135, 670, 772, 571, 268, 18, 3501, 19, 25889, 2135, 76, 772, 14432, 203, 1377, 389, 7175, 273, 315, 706, 6553, 3417, 177, 258, 247, 103, 14432, 203, 1377, 389, 31734, 273, 6549, 31, 203, 1377, 389, 4963, 3088, 1283, 273, 2130, 12648, 11706, 73, 2643, 31, 203, 203, 1377, 389, 2738, 12, 3576, 18, 15330, 16, 389, 4963, 3088, 1283, 16, 2080, 2738, 1769, 203, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-04 */ // SPDX-License-Identifier: MIT // # MysteriousWorld // Read more at https://www.themysterious.world/utility 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); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title 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); } /** * @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); } /** * @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); } } } } /** * @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; } } /** * @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); } } /** * @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; } } /** * @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 {} } /** * @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); } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // The Creature World and Superlative Secret Society is used so we check who holds a nft // for the free mint claim system interface Creature { function ownerOf(uint256 token) external view returns(address); function tokenOfOwnerByIndex(address inhabitant, uint256 index) external view returns(uint256); function balanceOf(address inhabitant) external view returns(uint256); } interface Superlative { function ownerOf(uint256 token) external view returns(address); function tokenOfOwnerByIndex(address inhabitant, uint256 index) external view returns(uint256); function balanceOf(address inhabitant) external view returns(uint256); } // The runes contract is used to burn for sacrifices and update balances on transfers interface IRunes { function burn(address inhabitant, uint256 cost) external; function updateRunes(address from, address to) external; } // Allows us to mint with $LOOKS instead of ETH interface Looks { function transferFrom(address from, address to, uint256 amount) external; function balanceOf(address owner) external view returns(uint256); } /* * o . ___---___ . * . .--\ --. . . . * ./.;_.\ __/~ \. * /; / `-' __\ . \ * . . / ,--' / . .; \ | * | .| / __ | -O- . * |__/ __ | . ; \ | . | | * | / \\_ . ;| \___| * . o | \ .~\\___,--' | . * | | . ; ~~~~\_ __| * | \ \ . . ; \ /_/ . * -O- . \ / . | ~/ . * | . ~\ \ . / /~ o * . ~--___ ; ___--~ * . --- . MYSTERIOUS WORLD */ contract MysteriousWorld is ERC721, Ownable { using Address for address; using Counters for Counters.Counter; Counters.Counter private Population; Counters.Counter private sacrificed; // tracks the amount of rituals performed Counters.Counter private sacred; // tracks the 1/1s created from rituals Creature public creature; Superlative public superlative; IRunes public runes; Looks public looks; string private baseURI; uint256 constant public maxInhabitants = 6666; uint256 constant public maxRituals = 3333; // max amount of rituals that can be performed uint256 constant public teamInhabitants = 66; // the amount of inhabitants that will be reserved to the teams wallet uint256 constant public maxWInhabitants = 900; // the amount of free inhabitants given to the community uint256 constant public maxFInhabitants = 100; // the amount of free inhabitants given to holders of superlative & creatureworld - fcfs basis uint256 constant public maxPerTxn = 6; uint256 public whitelistInhabitantsClaimed; // tracks the amount of mints claimed from giveaway winners uint256 public freeInhabitantsClaimed; // tracks the amount of free mints claimed from superlative & creatureworld holders uint256 public teamInhabitantsClaimed; // tracks the amount reserved for the team wallet uint256 public saleActive = 0; // the period for when public mint starts uint256 public claimActive = 0; // the period for free mint claiming - once the claimActive timestamp is reached, remaing supply goes to public fcfs uint256 public mintPrice = 0.06 ether; uint256 public ritualPrice = 100 ether; // base price for rituals is 100 $RUNES uint256 public ritualRate = 0.5 ether; // the rate increases the ritualPrice by the amount of rituals performed address public ritualWallet; // where the ritualized tokens go when u perform a ritual on them uint256 public looksPrice = 37 ether; // will be updated once contract is deployed if price difference is to high address public looksWallet; bool public templeAvailable = false; // once revealed, the temple will be available for rituals to be performed mapping(uint256 => bool) public ritualizedInhabitants; // tracks the tokens that survived the ritual process mapping(uint256 => bool) public uniqueInhabitants; // tracks the tokens that became gods mapping(address => uint256) public claimedW; // tracks to see what wallets claimed their whitelisted free mints mapping(address => uint256) public claimedF; // tracks to see what wallets claimed the free mints for the superlative & creatureworld event performRitualEvent(address caller, uint256 vessel, uint256 sacrifice); event performSacredRitualEvent(address caller, uint256 vessel, uint256 sacrifice); /* * # isTempleOpen * only allows you to perform a ritual if its enabled - this will be set after reveal */ modifier isTempleOpen() { require(templeAvailable, "The temple is not ready yet"); _; } /* * # inhabitantOwner * checks if you own the tokens your sacrificing */ modifier inhabitantOwner(uint256 inhabitant) { require(ownerOf(inhabitant) == msg.sender, "You can't use another persons inhabitants"); _; } /* * # ascendedOwner * checks if the inhabitant passed is ascended */ modifier ascendedOwner(uint256 inhabitant) { require(ritualizedInhabitants[inhabitant], "This inhabitant needs to sacrifice another inhabitant to ascend"); _; } /* * # isSaleActive * allows inhabitants to be sold... */ modifier isSaleActive() { require(block.timestamp > saleActive, "Inhabitants aren't born yet"); _; } /* * # isClaimActive * allows inhabitants to be taken for free... use this for the greater good */ modifier isClaimActive() { require(block.timestamp < claimActive, "All inhabitants are gone"); _; } constructor(address burner, address rare) ERC721("The Mysterious World", "The Mysterious World") { ritualWallet = burner; looksWallet = rare; } /* * # getAmountOfCreaturesHeld * returns the total amount of creature world nfts a wallet holds */ function getAmountOfCreaturesHeld(address holder) public view returns(uint256) { return creature.balanceOf(holder); } /* * # getAmountOfSuperlativesHeld * returns the total amount of superlatives nfts a wallet holds */ function getAmountOfSuperlativesHeld(address holder) public view returns(uint256) { return superlative.balanceOf(holder); } /* * # checkIfClaimedW * checks if the giveaway winners minted their tokens */ function checkIfClaimedW(address holder) public view returns(uint256) { return claimedW[holder]; } /* * # checkIfClaimedF * checks if the superlative and creature holders minted their free tokens */ function checkIfClaimedF(address holder) public view returns(uint256) { return claimedF[holder]; } /* * # addWhitelistWallets * adds the addresses to claimedW while setting the amount each address can claim */ function addWhitelistWallets(address[] calldata winners) external payable onlyOwner { for (uint256 wallet;wallet < winners.length;wallet++) { claimedW[winners[wallet]] = 1; } } /* * # mint * mints a inhabitant - godspeed */ function mint(uint256 amount) public payable isSaleActive { require(tx.origin == msg.sender, "Can't mint from other contracts!"); require(amount > 0 && amount <= maxPerTxn, "Your amount must be between 1 and 6"); if (block.timestamp <= claimActive) { require(Population.current() + amount <= (maxInhabitants - (maxWInhabitants + maxFInhabitants)), "Not enough inhabitants for that"); } else { require(Population.current() + amount <= maxInhabitants, "Not enough inhabitants for that"); } require(mintPrice * amount == msg.value, "Mint Price is not correct"); for (uint256 i = 0;i < amount;i++) { _safeMint(msg.sender, Population.current()); Population.increment(); } } /* * # mintWhitelist * mints a free inhabitant from the whitelist wallets */ function mintWhitelist() public payable isSaleActive isClaimActive { uint256 currentInhabitants = Population.current(); require(tx.origin == msg.sender, "Can't mint from other contracts!"); require(currentInhabitants + 1 <= maxInhabitants, "No inhabitants left"); require(whitelistInhabitantsClaimed + 1 <= maxWInhabitants, "No inhabitants left"); require(claimedW[msg.sender] == 1, "You don't have permission to be here outsider"); _safeMint(msg.sender, currentInhabitants); Population.increment(); claimedW[msg.sender] = 0; whitelistInhabitantsClaimed++; delete currentInhabitants; } /* * # mintFList * mints a free inhabitant if your holding a creature world or superlative token - can only be claimed once fcfs */ function mintFList() public payable isSaleActive isClaimActive { uint256 currentInhabitants = Population.current(); require(tx.origin == msg.sender, "Can't mint from other contracts!"); require(currentInhabitants + 1 <= maxInhabitants, "No inhabitants left"); require(freeInhabitantsClaimed + 1 <= maxFInhabitants, "No inhabitants left"); require(getAmountOfCreaturesHeld(msg.sender) >= 1 || getAmountOfSuperlativesHeld(msg.sender) >= 1, "You don't have permission to be here outsider"); require(claimedF[msg.sender] < 1, "You already took a inhabitant"); _safeMint(msg.sender, currentInhabitants); Population.increment(); claimedF[msg.sender] = 1; freeInhabitantsClaimed++; delete currentInhabitants; } /* * # mintWithLooks * allows you to mint with $LOOKS token - still need to pay gas :( */ function mintWithLooks(uint256 amount) public payable isSaleActive { uint256 currentInhabitants = Population.current(); require(tx.origin == msg.sender, "Can't mint from other contracts!"); require(amount > 0 && amount <= maxPerTxn, "Your amount must be between 1 and 6"); if (block.timestamp <= claimActive) { require(currentInhabitants + amount <= (maxInhabitants - (maxWInhabitants + maxFInhabitants)), "Not enough inhabitants for that"); } else { require(currentInhabitants + amount <= maxInhabitants, "Not enough inhabitants for that"); } require(looks.balanceOf(msg.sender) >= looksPrice * amount, "Not enough $LOOKS to buy a inhabitant"); looks.transferFrom(msg.sender, looksWallet, looksPrice * amount); for (uint256 i = 0;i < amount;i++) { _safeMint(msg.sender, currentInhabitants + i); Population.increment(); } delete currentInhabitants; } /* * # reserveInhabitants * mints the amount provided for the team wallet - the amount is capped by teamInhabitants */ function reserveInhabitants(uint256 amount) public payable onlyOwner { uint256 currentInhabitants = Population.current(); require(teamInhabitantsClaimed + amount < teamInhabitants, "We've run out of inhabitants for the team"); for (uint256 i = 0;i < amount;i++) { _safeMint(msg.sender, currentInhabitants + i); Population.increment(); teamInhabitantsClaimed++; } delete currentInhabitants; } /* * # performRitual * performing the ritual will burn one of the tokens passed and upgrade the first token passed. upgrading will * change the metadata of the image and add to the sacrifice goals for the project. */ function performRitual(uint256 vessel, uint256 sacrifice) public payable inhabitantOwner(vessel) inhabitantOwner(sacrifice) isTempleOpen { require(vessel != sacrifice, "You can't sacrifice the same inhabitants"); require(!ritualizedInhabitants[vessel] && !ritualizedInhabitants[sacrifice], "You can't sacrifice ascended inhabitants with those of the lower class"); // burn the $RUNES and transfer the sacrificed token to the burn wallet runes.burn(msg.sender, ritualPrice + (ritualRate * sacrificed.current())); safeTransferFrom(msg.sender, ritualWallet, sacrifice, ""); // track the tokens that ascended & add to the global goal sacrificed.increment(); ritualizedInhabitants[vessel] = true; emit performRitualEvent(msg.sender, vessel, sacrifice); } /* * # performSacredRight * this is performed during the 10% sacrifical goals for the 1/1s. check the utility page for more info */ function performSacredRitual(uint256 vessel, uint256 sacrifice) public payable inhabitantOwner(vessel) inhabitantOwner(sacrifice) ascendedOwner(vessel) ascendedOwner(sacrifice) isTempleOpen { uint256 currentGoal = 333 * sacred.current(); // 10% of maxRituals require(vessel != sacrifice, "You can't sacrifice the same inhabitants"); require(sacrificed.current() >= currentGoal, "Not enough sacrifices to discover a God!"); // burn the $RUNES and transfer the sacrificed token to the burn wallet runes.burn(msg.sender, ritualPrice + (ritualRate * sacrificed.current())); safeTransferFrom(msg.sender, ritualWallet, sacrifice, ""); ritualizedInhabitants[vessel] = false; uniqueInhabitants[vessel] = true; sacrificed.increment(); sacred.increment(); emit performSacredRitualEvent(msg.sender, vessel, sacrifice); } /* * # getCaptives * returns all the tokens a wallet holds */ function getCaptives(address inhabitant) public view returns(uint256[] memory) { uint256 population = Population.current(); uint256 amount = balanceOf(inhabitant); uint256 selector = 0; uint256[] memory inhabitants = new uint256[](amount); for (uint256 i = 0;i < population;i++) { if (ownerOf(i) == inhabitant) { inhabitants[selector] = i; selector++; } } return inhabitants; } /* * # totalSupply */ function totalSupply() external view returns(uint256) { return Population.current(); } /* * # getSacrificed */ function getSacrificed() external view returns(uint256) { return sacrificed.current(); } /* * # getSacred */ function getSacred() external view returns(uint256) { return sacred.current(); } /* * # _baseURI */ function _baseURI() internal view override returns (string memory) { return baseURI; } /* * # setBaseURI */ function setBaseURI(string memory metadataUrl) public payable onlyOwner { baseURI = metadataUrl; } /* * # withdraw * withdraws the funds from the smart contract to the owner */ function withdraw() public payable onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); delete balance; } /* * # setSaleSettings * sets the drop time and the claimimg time */ function setSaleSettings(uint256 saleTime, uint256 claimTime) public payable onlyOwner { saleActive = saleTime; claimActive = claimTime; } /* * # setMintPrice * sets the mint price for the sale incase we need to change it */ function setMintPrice(uint256 price) public payable onlyOwner { mintPrice = price; } /* * # setLooksPrice * sets the price of $LOOKS to mint with incase we need to set it multiple times */ function setLooksPrice(uint256 price) public payable onlyOwner { looksPrice = price; } /* * # setRitualSettings * allows us to change the ritual price, rate, and whether ritual is enabled or not */ function setRitualSettings(uint256 price, uint256 rate, bool available) public payable onlyOwner { ritualPrice = price; ritualRate = rate; templeAvailable = available; } /* * # setCollectionInterfaces * sets the interfaces for creatureworld, superlative, and runes */ function setCollectionInterfaces(address creatureContract, address superlativeContract, address runesContract, address looksContract) public payable onlyOwner { creature = Creature(creatureContract); superlative = Superlative(superlativeContract); runes = IRunes(runesContract); looks = Looks(looksContract); } /* * # transferFrom */ function transferFrom(address from, address to, uint256 inhabitant) public override { runes.updateRunes(from, to); ERC721.transferFrom(from, to, inhabitant); } /* * # safeTransferFrom */ function safeTransferFrom(address from, address to, uint256 inhabitant) public override { safeTransferFrom(from, to, inhabitant, ""); } function safeTransferFrom(address from, address to, uint256 inhabitant, bytes memory data) public override { runes.updateRunes(from, to); ERC721.safeTransferFrom(from, to, inhabitant, data); } }
The runes contract is used to burn for sacrifices and update balances on transfers
interface IRunes { function burn(address inhabitant, uint256 cost) external; function updateRunes(address from, address to) external; }
15,317,096
[ 1, 1986, 24188, 6835, 353, 1399, 358, 18305, 364, 20071, 86, 430, 1242, 471, 1089, 324, 26488, 603, 29375, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 1997, 281, 288, 203, 565, 445, 18305, 12, 2867, 316, 76, 30258, 970, 16, 2254, 5034, 6991, 13, 3903, 31, 203, 565, 445, 1089, 1997, 281, 12, 2867, 628, 16, 1758, 358, 13, 3903, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/100/0x817286ebB5b80D4c857D345423A494fc082021Eb/sources/BlockRewardAuRa.sol
@dev Generates and distributes rewards according to the logic and formulas described in the POSDAO white paper. =============================================== Storage ======================================================== WARNING: since this contract is upgradeable, do not remove existing storage variables, do not change their order, and do not change their types!
contract BlockRewardAuRaBase is UpgradeableOwned, IBlockRewardAuRa { using SafeMath for uint256; mapping(address => uint256[]) internal _epochsPoolGotRewardFor; mapping(address => bool) internal _ercToNativeBridgeAllowed; address[] internal _ercToNativeBridgesAllowed; IBlockRewardAuRa internal _prevBlockRewardContract; bool internal _queueERInitialized; uint256 internal _queueERFirst; uint256 internal _queueERLast; struct ExtraReceiverQueue { uint256 amount; address bridge; address receiver; } mapping(uint256 => ExtraReceiverQueue) internal _queueER; uint256[25] private ______gapForInternal; mapping(uint256 => mapping(address => uint256)) public blocksCreated; uint256 public bridgeNativeReward; mapping(uint256 => mapping(address => uint256)) public epochPoolNativeReward; mapping(address => uint256) public mintedForAccount; mapping(address => mapping(uint256 => uint256)) public mintedForAccountInBlock; mapping(uint256 => uint256) public mintedInBlock; uint256 public mintedTotally; mapping(address => uint256) public mintedTotallyByBridge; uint256 public nativeRewardUndistributed; mapping(uint256 => mapping(address => uint256)) public snapshotPoolTotalStakeAmount; mapping(uint256 => mapping(address => uint256)) public snapshotPoolValidatorStakeAmount; mapping(uint256 => uint256) public validatorMinRewardPercent; IValidatorSetAuRa public validatorSetContract; uint256[25] private ______gapForPublic; event AddedReceiver(uint256 amount, address indexed receiver, address indexed bridge); event BridgeNativeRewardAdded(uint256 amount, uint256 cumulativeAmount, address indexed bridge); event MintedNative(address[] receivers, uint256[] rewards); modifier onlyErcToNativeBridge { require(_ercToNativeBridgeAllowed[msg.sender]); _; } modifier onlyInitialized { require(isInitialized()); _; } modifier onlySystem { require(msg.sender == 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE); _; } modifier onlyStakingContract() { require(msg.sender == address(validatorSetContract.stakingContract())); _; } modifier onlyValidatorSetContract() { require(msg.sender == address(validatorSetContract)); _; } function () payable external { revert(); } function addBridgeNativeFeeReceivers(uint256 _amount) external { addBridgeNativeRewardReceivers(_amount); } function addBridgeNativeRewardReceivers(uint256 _amount) public onlyErcToNativeBridge { require(_amount != 0); bridgeNativeReward = bridgeNativeReward.add(_amount); emit BridgeNativeRewardAdded(_amount, bridgeNativeReward, msg.sender); } function addExtraReceiver(uint256 _amount, address _receiver) external onlyErcToNativeBridge { require(_amount != 0); require(_queueERInitialized); _enqueueExtraReceiver(_amount, _receiver, msg.sender); emit AddedReceiver(_amount, _receiver, msg.sender); } function clearBlocksCreated() external onlyValidatorSetContract { IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); address[] memory validators = _getCurrentValidators(); for (uint256 i = 0; i < validators.length; i++) { blocksCreated[stakingEpoch][validators[i]] = 0; } } function clearBlocksCreated() external onlyValidatorSetContract { IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); address[] memory validators = _getCurrentValidators(); for (uint256 i = 0; i < validators.length; i++) { blocksCreated[stakingEpoch][validators[i]] = 0; } } function initialize(address _validatorSet, address _prevBlockReward) external { require(_getCurrentBlockNumber() == 0 || msg.sender == _admin()); require(!isInitialized()); require(_validatorSet != address(0)); validatorSetContract = IValidatorSetAuRa(_validatorSet); validatorMinRewardPercent[0] = VALIDATOR_MIN_REWARD_PERCENT; _prevBlockRewardContract = IBlockRewardAuRa(_prevBlockReward); } function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } IRandomAuRa(validatorSetContract.randomContract()).onFinishCollectRound(); function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } validatorSetContract.newValidatorSet(); uint256 i; miningAddresses = validatorSetContract.getPendingValidators(); function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } miningAddresses = validatorSetContract.getValidators(); function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } (miningAddresses, ) = validatorSetContract.validatorsToBeFinalized(); function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { address stakingAddress = validatorSetContract.stakingByMiningAddress(benefactors[0]); blocksCreated[stakingEpoch][stakingAddress]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } } } validatorMinRewardPercent[nextStakingEpoch] = VALIDATOR_MIN_REWARD_PERCENT; bridgeQueueLimit = 0; return _mintNativeCoins(nativeTotalRewardAmount, bridgeQueueLimit); function setErcToNativeBridgesAllowed(address[] calldata _bridgesAllowed) external onlyOwner onlyInitialized { uint256 i; for (i = 0; i < _ercToNativeBridgesAllowed.length; i++) { _ercToNativeBridgeAllowed[_ercToNativeBridgesAllowed[i]] = false; } _ercToNativeBridgesAllowed = _bridgesAllowed; for (i = 0; i < _bridgesAllowed.length; i++) { _ercToNativeBridgeAllowed[_bridgesAllowed[i]] = true; } } function setErcToNativeBridgesAllowed(address[] calldata _bridgesAllowed) external onlyOwner onlyInitialized { uint256 i; for (i = 0; i < _ercToNativeBridgesAllowed.length; i++) { _ercToNativeBridgeAllowed[_ercToNativeBridgesAllowed[i]] = false; } _ercToNativeBridgesAllowed = _bridgesAllowed; for (i = 0; i < _bridgesAllowed.length; i++) { _ercToNativeBridgeAllowed[_bridgesAllowed[i]] = true; } } function setErcToNativeBridgesAllowed(address[] calldata _bridgesAllowed) external onlyOwner onlyInitialized { uint256 i; for (i = 0; i < _ercToNativeBridgesAllowed.length; i++) { _ercToNativeBridgeAllowed[_ercToNativeBridgesAllowed[i]] = false; } _ercToNativeBridgesAllowed = _bridgesAllowed; for (i = 0; i < _bridgesAllowed.length; i++) { _ercToNativeBridgeAllowed[_bridgesAllowed[i]] = true; } } function blockRewardContractId() public pure returns(bytes4) { } function currentNativeRewardToDistribute( IStakingAuRa _stakingContract, uint256 _stakingEpoch, uint256 _totalRewardShareNum, uint256 _totalRewardShareDenom, address[] memory _validators ) public view returns(uint256, uint256) { return _currentRewardToDistribute( _getTotalNativeReward(_stakingEpoch, _validators), _stakingContract, _totalRewardShareNum, _totalRewardShareDenom ); } function currentPoolRewards( uint256 _rewardToDistribute, uint256[] memory _blocksCreatedShareNum, uint256 _blocksCreatedShareDenom, uint256 _stakingEpoch ) public view returns(uint256[] memory) { uint256[] memory poolRewards; if (_blocksCreatedShareDenom == 0) { (_blocksCreatedShareNum, _blocksCreatedShareDenom) = _blocksShareNumDenom(_stakingEpoch, new address[](0)); } if (_rewardToDistribute == 0 || _blocksCreatedShareDenom == 0) { poolRewards = new uint256[](0); poolRewards = new uint256[](_blocksCreatedShareNum.length); for (uint256 i = 0; i < _blocksCreatedShareNum.length; i++) { poolRewards[i] = _rewardToDistribute * _blocksCreatedShareNum[i] / _blocksCreatedShareDenom; } } return poolRewards; } function currentPoolRewards( uint256 _rewardToDistribute, uint256[] memory _blocksCreatedShareNum, uint256 _blocksCreatedShareDenom, uint256 _stakingEpoch ) public view returns(uint256[] memory) { uint256[] memory poolRewards; if (_blocksCreatedShareDenom == 0) { (_blocksCreatedShareNum, _blocksCreatedShareDenom) = _blocksShareNumDenom(_stakingEpoch, new address[](0)); } if (_rewardToDistribute == 0 || _blocksCreatedShareDenom == 0) { poolRewards = new uint256[](0); poolRewards = new uint256[](_blocksCreatedShareNum.length); for (uint256 i = 0; i < _blocksCreatedShareNum.length; i++) { poolRewards[i] = _rewardToDistribute * _blocksCreatedShareNum[i] / _blocksCreatedShareDenom; } } return poolRewards; } function currentPoolRewards( uint256 _rewardToDistribute, uint256[] memory _blocksCreatedShareNum, uint256 _blocksCreatedShareDenom, uint256 _stakingEpoch ) public view returns(uint256[] memory) { uint256[] memory poolRewards; if (_blocksCreatedShareDenom == 0) { (_blocksCreatedShareNum, _blocksCreatedShareDenom) = _blocksShareNumDenom(_stakingEpoch, new address[](0)); } if (_rewardToDistribute == 0 || _blocksCreatedShareDenom == 0) { poolRewards = new uint256[](0); poolRewards = new uint256[](_blocksCreatedShareNum.length); for (uint256 i = 0; i < _blocksCreatedShareNum.length; i++) { poolRewards[i] = _rewardToDistribute * _blocksCreatedShareNum[i] / _blocksCreatedShareDenom; } } return poolRewards; } } else { function currentPoolRewards( uint256 _rewardToDistribute, uint256[] memory _blocksCreatedShareNum, uint256 _blocksCreatedShareDenom, uint256 _stakingEpoch ) public view returns(uint256[] memory) { uint256[] memory poolRewards; if (_blocksCreatedShareDenom == 0) { (_blocksCreatedShareNum, _blocksCreatedShareDenom) = _blocksShareNumDenom(_stakingEpoch, new address[](0)); } if (_rewardToDistribute == 0 || _blocksCreatedShareDenom == 0) { poolRewards = new uint256[](0); poolRewards = new uint256[](_blocksCreatedShareNum.length); for (uint256 i = 0; i < _blocksCreatedShareNum.length; i++) { poolRewards[i] = _rewardToDistribute * _blocksCreatedShareNum[i] / _blocksCreatedShareDenom; } } return poolRewards; } function epochsPoolGotRewardFor(address _stakingAddress) public view returns(uint256[] memory) { return _epochsPoolGotRewardFor[_stakingAddress]; } function ercToNativeBridgesAllowed() public view returns(address[] memory) { return _ercToNativeBridgesAllowed; } function extraReceiversQueueSize() public view returns(uint256) { return _queueERLast + 1 - _queueERFirst; } function isInitialized() public view returns(bool) { return validatorSetContract != IValidatorSetAuRa(0); } function onTokenTransfer(address, uint256, bytes memory) public pure returns(bool) { revert(); } function epochsToClaimRewardFrom( address _poolStakingAddress, address _staker ) public view returns(uint256[] memory epochsToClaimFrom) { require(_poolStakingAddress != address(0)); require(_staker != address(0)); IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); uint256 firstEpoch; uint256 lastEpoch; firstEpoch = stakingContract.stakeFirstEpoch(_poolStakingAddress, _staker); if (firstEpoch == 0) { return (new uint256[](0)); } lastEpoch = stakingContract.stakeLastEpoch(_poolStakingAddress, _staker); } uint256[] storage epochs = _epochsPoolGotRewardFor[_poolStakingAddress]; uint256 length = epochs.length; uint256[] memory tmp = new uint256[](length); uint256 tmpLength = 0; uint256 i; function epochsToClaimRewardFrom( address _poolStakingAddress, address _staker ) public view returns(uint256[] memory epochsToClaimFrom) { require(_poolStakingAddress != address(0)); require(_staker != address(0)); IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); uint256 firstEpoch; uint256 lastEpoch; firstEpoch = stakingContract.stakeFirstEpoch(_poolStakingAddress, _staker); if (firstEpoch == 0) { return (new uint256[](0)); } lastEpoch = stakingContract.stakeLastEpoch(_poolStakingAddress, _staker); } uint256[] storage epochs = _epochsPoolGotRewardFor[_poolStakingAddress]; uint256 length = epochs.length; uint256[] memory tmp = new uint256[](length); uint256 tmpLength = 0; uint256 i; for (i = 0; i < length; i++) { uint256 epoch = epochs[i]; if (epoch < firstEpoch) { continue; } if (lastEpoch <= epoch && lastEpoch != 0) { break; } } for (i = 0; i < length; i++) { uint256 epoch = epochs[i]; if (epoch < firstEpoch) { continue; } if (lastEpoch <= epoch && lastEpoch != 0) { break; } } for (i = 0; i < length; i++) { uint256 epoch = epochs[i]; if (epoch < firstEpoch) { continue; } if (lastEpoch <= epoch && lastEpoch != 0) { break; } } if (!stakingContract.rewardWasTaken(_poolStakingAddress, delegatorOrZero, epoch)) { tmp[tmpLength++] = epoch; } }
16,675,192
[ 1, 6653, 471, 1015, 1141, 283, 6397, 4888, 358, 326, 4058, 471, 646, 24857, 11893, 316, 326, 12511, 18485, 9578, 15181, 18, 422, 4428, 14468, 33, 5235, 422, 20775, 894, 631, 9744, 30, 3241, 333, 6835, 353, 8400, 429, 16, 741, 486, 1206, 2062, 2502, 3152, 16, 741, 486, 2549, 3675, 1353, 16, 471, 741, 486, 2549, 3675, 1953, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3914, 17631, 1060, 37, 89, 12649, 2171, 353, 17699, 429, 5460, 329, 16, 467, 1768, 17631, 1060, 37, 89, 12649, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 63, 5717, 2713, 389, 28530, 2864, 15617, 17631, 1060, 1290, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 2713, 389, 12610, 774, 9220, 13691, 5042, 31, 203, 565, 1758, 8526, 2713, 389, 12610, 774, 9220, 38, 1691, 2852, 5042, 31, 203, 565, 467, 1768, 17631, 1060, 37, 89, 12649, 2713, 389, 10001, 1768, 17631, 1060, 8924, 31, 203, 565, 1426, 2713, 389, 4000, 654, 11459, 31, 203, 565, 2254, 5034, 2713, 389, 4000, 654, 3759, 31, 203, 565, 2254, 5034, 2713, 389, 4000, 654, 3024, 31, 203, 565, 1958, 13592, 12952, 3183, 288, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 1758, 10105, 31, 203, 3639, 1758, 5971, 31, 203, 565, 289, 203, 565, 2874, 12, 11890, 5034, 516, 13592, 12952, 3183, 13, 2713, 389, 4000, 654, 31, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 2254, 5034, 63, 2947, 65, 3238, 389, 7198, 67, 14048, 1290, 3061, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 4398, 6119, 31, 203, 565, 2254, 5034, 1071, 10105, 9220, 17631, 1060, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 7632, 2864, 9220, 17631, 1060, 31, 2 ]
./partial_match/42/0xF3cCFb9c0ba0AeDa18306eeacAe569dc29Bb2d39/sources/contracts/BitbaseLGE.sol
30% of ETH is used to market purchase DEFLCT
function addLiquidity() public payable { require(now < lgeEndTime && lgeStarted, "Liquidity Generation Event over or not started yet"); ETHContributedForBonusTokens[msg.sender] = ethContributedForLPTokens[msg.sender]; uint256 ethForBuyingDeflect = msg.value.div(100).mul(30); ethUsedForDeflectPair = ethUsedForDeflectPair.add(ethForBuyingDeflect); uint256 deadline = block.timestamp + 15; address[] memory path = new address[](2); path[0] = WETH; path[1] = DEFLCT; require(IERC20(DEFLCT).approve(address(uniswapRouterV2), uint256(-1)), "Approval issue"); totalETHContributed = totalETHContributed.add(msg.value); emit LiquidityAddition(msg.sender, msg.value); }
3,414,965
[ 1, 5082, 9, 434, 512, 2455, 353, 1399, 358, 13667, 23701, 2030, 19054, 1268, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 527, 48, 18988, 24237, 1435, 1071, 8843, 429, 288, 203, 565, 2583, 12, 3338, 411, 328, 908, 25255, 597, 328, 908, 9217, 16, 315, 48, 18988, 24237, 23234, 2587, 1879, 578, 486, 5746, 4671, 8863, 203, 565, 512, 2455, 442, 11050, 1290, 38, 22889, 5157, 63, 3576, 18, 15330, 65, 273, 13750, 442, 11050, 1290, 48, 1856, 3573, 63, 3576, 18, 15330, 15533, 203, 203, 565, 2254, 5034, 13750, 1290, 38, 9835, 310, 3262, 1582, 273, 1234, 18, 1132, 18, 2892, 12, 6625, 2934, 16411, 12, 5082, 1769, 203, 565, 13750, 6668, 1290, 3262, 1582, 4154, 273, 13750, 6668, 1290, 3262, 1582, 4154, 18, 1289, 12, 546, 1290, 38, 9835, 310, 3262, 1582, 1769, 203, 203, 565, 2254, 5034, 14096, 273, 1203, 18, 5508, 397, 4711, 31, 203, 565, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 565, 589, 63, 20, 65, 273, 678, 1584, 44, 31, 203, 565, 589, 63, 21, 65, 273, 2030, 19054, 1268, 31, 203, 203, 565, 2583, 12, 45, 654, 39, 3462, 12, 12904, 48, 1268, 2934, 12908, 537, 12, 2867, 12, 318, 291, 91, 438, 8259, 58, 22, 3631, 2254, 5034, 19236, 21, 13, 3631, 315, 23461, 5672, 8863, 203, 203, 565, 2078, 1584, 44, 442, 11050, 273, 2078, 1584, 44, 442, 11050, 18, 1289, 12, 3576, 18, 1132, 1769, 203, 565, 3626, 511, 18988, 24237, 30296, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; // the erc1155 base contract - the openzeppelin erc1155 import "../token/ERC721A/ERC721A.sol"; import "../royalties/ERC2981.sol"; import "../utils/AddressSet.sol"; import "../utils/UInt256Set.sol"; import "./ProxyRegistry.sol"; import "../access/Controllable.sol"; import "../interfaces/IMultiToken.sol"; import "../interfaces/IERC1155Mint.sol"; import "../interfaces/IERC1155Burn.sol"; import "../interfaces/IERC1155Multinetwork.sol"; import "../interfaces/IERC1155Bridge.sol"; import "../service/Service.sol"; import "../factories/FactoryElement.sol"; /** * @title MultiToken * @notice the multitoken contract. All tokens are printed on this contract. The token has all the capabilities * of an erc1155 contract, plus network transfer, royallty tracking and assignment and other features. */ contract MultiToken721 is ERC721A, ProxyRegistryManager, IERC1155Multinetwork, IMultiToken, ERC2981, Service, Controllable, Initializable, FactoryElement { // to work with token holder and held token lists using AddressSet for AddressSet.Set; using UInt256Set for UInt256Set.Set; using Strings for uint256; address internal masterMinter; string internal _uri; function initialize(address registry) public initializer { _addController(msg.sender); _serviceRegistry = registry; } function initToken(string memory symbol, string memory name) public { _initToken(symbol, name); } function setMasterController(address _masterMinter) public { require(masterMinter == address(0), "master minter must not be set"); masterMinter = _masterMinter; _addController(_masterMinter); } function addDirectMinter(address directMinter) public { require(msg.sender == masterMinter, "only master minter can add direct minters"); _addController(directMinter); } /// @notice only allow owner of the contract modifier onlyOwner() { require(_isController(msg.sender), "You shall not pass"); _; } /// @notice only allow owner of the contract modifier onlyMinter() { require(_isController(msg.sender) || masterMinter == msg.sender, "You shall not pass"); _; } /// @notice Mint a specified amount the specified token hash to the specified receiver /// @param recipient the address of the receiver /// @param amount the amount to mint function mint( address recipient, uint256, uint256 amount ) external override onlyMinter { _mint(recipient, amount, "", true); } /// @notice mint tokens of specified amount to the specified address /// @param recipient the mint target /// @param amount the amount to mint function mintWithCommonUri( address recipient, uint256, uint256 amount, uint256 ) external onlyMinter { _mint(recipient, amount, "", true); } string internal baseUri; function setBaseURI(string memory value) external onlyMinter { baseUri = value; } function baseURI() external view returns (string memory) { return _baseURI(); } function _baseURI() internal view virtual override returns (string memory) { return baseUri; } /// @notice burn a specified amount of the specified token hash from the specified target /// @param tokenHash the token id to burn function burn( address, uint256 tokenHash, uint256 ) external override onlyMinter { _burn(tokenHash); } /// @notice override base functionality to check proxy registries for approvers /// @param _owner the owner address /// @param _operator the operator address /// @return isOperator true if the owner is an approver for the operator function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // check proxy whitelist bool _approved = _isApprovedForAll(_owner, _operator); return _approved || ERC721A.isApprovedForAll(_owner, _operator); } /// @notice See {IERC165-supportsInterface}. ERC165 implementor. identifies this contract as an ERC1155 /// @param interfaceId the interface id to check function supportsInterface(bytes4 interfaceId) public view virtual override(ERC2981, ERC721A) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /// @notice perform a network token transfer. Transfer the specified quantity of the specified token hash to the destination address on the destination network. function networkTransferFrom( address from, address to, uint256 network, uint256 id, uint256 amount, bytes calldata data ) external virtual override { address _bridge = IJanusRegistry(_serviceRegistry).get("MultiToken", "NetworkBridge"); require(_bridge != address(0), "No network bridge found"); // call the network transfer on the bridge IERC1155Multinetwork(_bridge).networkTransferFrom(from, to, network, id, amount, data); } mapping(uint256 => string) internal symbolsOf; mapping(uint256 => string) internal namesOf; function symbolOf(uint256 _tokenId) external view override returns (string memory out) { return symbolsOf[_tokenId]; } function nameOf(uint256 _tokenId) external view override returns (string memory out) { return namesOf[_tokenId]; } function setSymbolOf(uint256 _tokenId, string memory _symbolOf) external onlyMinter { symbolsOf[_tokenId] = _symbolOf; } function setNameOf(uint256 _tokenId, string memory _nameOf) external onlyMinter { namesOf[_tokenId] = _nameOf; } function setRoyalty(uint256 tokenId, address receiver, uint256 amount) external onlyOwner { royaltyReceiversByHash[tokenId] = receiver; royaltyFeesByHash[tokenId] = amount; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // 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 // 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/token/ERC721/extensions/IERC721Enumerable.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 MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // 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; function _initToken(string memory name_, string memory symbol_) internal { require(bytes(_name).length == 0, "ERC721 token name already set"); _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "../interfaces/IERC2981Holder.sol"; import "../interfaces/IERC2981.sol"; /// /// @dev An implementor for the NFT Royalty Standard. Provides interface /// response to erc2981 as well as a way to modify the royalty fees /// per token and a way to transfer ownership of a token. /// abstract contract ERC2981 is ERC165, IERC2981, IERC2981Holder { // royalty receivers by token hash mapping(uint256 => address) internal royaltyReceiversByHash; // royalties for each token hash - expressed as permilliage of total supply mapping(uint256 => uint256) internal royaltyFeesByHash; bytes4 internal constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// @dev only the royalty owner shall pass modifier onlyRoyaltyOwner(uint256 _id) { require(royaltyReceiversByHash[_id] == msg.sender, "Only the owner can modify the royalty fees"); _; } /** * @dev ERC2981 - return the receiver and royalty payment given the id and sale price * @param _tokenId the id of the token * @param _salePrice the price of the token * @return receiver the receiver * @return royaltyAmount the royalty payment */ function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view override returns ( address receiver, uint256 royaltyAmount ) { require(_salePrice > 0, "Sale price must be greater than 0"); require(_tokenId > 0, "Token Id must be valid"); // get the receiver of the royalty receiver = royaltyReceiversByHash[_tokenId]; // calculate the royalty amount. royalty is expressed as permilliage of total supply royaltyAmount = royaltyFeesByHash[_tokenId] / 1000000 * _salePrice; } /// @notice ERC165 interface responder for this contract /// @param interfaceId - the interface id to check /// @return supportsIface - whether the interface is supported function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool supportsIface) { supportsIface = interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /// @notice set the fee permilliage for a token hash /// @param _id - id of the token hash /// @param _fee - the fee permilliage to set function setFee(uint256 _id, uint256 _fee) onlyRoyaltyOwner(_id) external override { require(_id != 0, "Fee cannot be zero"); royaltyFeesByHash[_id] = _fee; } /// @notice get the fee permilliage for a token hash /// @param _id - id of the token hash /// @return fee - the fee function getFee(uint256 _id) external view override returns (uint256 fee) { fee = royaltyFeesByHash[_id]; } /// @notice get the royalty receiver for a token hash /// @param _id - id of the token hash /// @return owner - the royalty owner function royaltyOwner(uint256 _id) external view override returns (address owner) { owner = royaltyReceiversByHash[_id]; } /// @notice get the royalty receiver for a token hash /// @param _id - id of the token hash /// @param _newOwner - address of the new owners function transferOwnership(uint256 _id, address _newOwner) onlyRoyaltyOwner(_id) external override { require(_id != 0 && _newOwner != address(0), "Invalid token id or new owner"); royaltyReceiversByHash[_id] = _newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /** * @notice Key sets with enumeration and delete. Uses mappings for random * and existence checks and dynamic arrays for enumeration. Key uniqueness is enforced. * @dev Sets are unordered. Delete operations reorder keys. All operations have a * fixed gas cost at any scale, O(1). * author: Rob Hitchens */ library AddressSet { struct Set { mapping(address => uint256) keyPointers; address[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, address key) public { require( !exists(self, key), "AddressSet: key already exists in the set." ); self.keyList.push(key); self.keyPointers[key] = self.keyList.length - 1; } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, address key) public { // TODO: I commented this out do get a test to pass - need to figure out what is up here require( exists(self, key), "AddressSet: key does not exist in the set." ); if (!exists(self, key)) return; uint256 last = count(self) - 1; uint256 rowToReplace = self.keyPointers[key]; if (rowToReplace != last) { address keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) public view returns (uint256) { return (self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, address key) public view returns (bool) { if (self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint256 index) public view returns (address) { return self.keyList[index]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /** * @notice Key sets with enumeration and delete. Uses mappings for random * and existence checks and dynamic arrays for enumeration. Key uniqueness is enforced. * @dev Sets are unordered. Delete operations reorder keys. All operations have a * fixed gas cost at any scale, O(1). * author: Rob Hitchens */ library UInt256Set { struct Set { mapping(uint256 => uint256) keyPointers; uint256[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, uint256 key) public { require( !exists(self, key), "UInt256Set: key already exists in the set." ); self.keyList.push(key); self.keyPointers[key] = self.keyList.length - 1; } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, uint256 key) public { // TODO: I commented this out do get a test to pass - need to figure out what is up here // require( // exists(self, key), // "UInt256Set: key does not exist in the set." // ); if (!exists(self, key)) return; uint256 last = count(self) - 1; uint256 rowToReplace = self.keyPointers[key]; if (rowToReplace != last) { uint256 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; delete self.keyList[self.keyList.length - 1]; } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) public view returns (uint256) { return (self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, uint256 key) public view returns (bool) { if (self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint256 index) public view returns (uint256) { return self.keyList[index]; } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "../interfaces/IProxyRegistry.sol"; import "../utils/AddressSet.sol"; /// @title ProxyRegistryManager /// @notice a proxy registry is a registry of delegate proxies which have the ability to autoapprove transactions for some address / contract. Used by OpenSEA to enable feeless trades by a proxy account contract ProxyRegistryManager is IProxyRegistryManager { // using the addressset library to store the addresses of the proxies using AddressSet for AddressSet.Set; // the set of registry managers able to manage this registry mapping(address => bool) internal registryManagers; // the set of proxy addresses AddressSet.Set private _proxyAddresses; /// @notice add a new registry manager to the registry /// @param newManager the address of the registry manager to add function addRegistryManager(address newManager) external virtual override { registryManagers[newManager] = true; } /// @notice remove a registry manager from the registry /// @param oldManager the address of the registry manager to remove function removeRegistryManager(address oldManager) external virtual override { registryManagers[oldManager] = false; } /// @notice check if an address is a registry manager /// @param _addr the address of the registry manager to check /// @return _isManager true if the address is a registry manager, false otherwise function isRegistryManager(address _addr) external virtual view override returns (bool _isManager) { return registryManagers[_addr]; } /// @notice add a new proxy address to the registry /// @param newProxy the address of the proxy to add function addProxy(address newProxy) external virtual override { _proxyAddresses.insert(newProxy); } /// @notice remove a proxy address from the registry /// @param oldProxy the address of the proxy to remove function removeProxy(address oldProxy) external virtual override { _proxyAddresses.remove(oldProxy); } /// @notice check if an address is a proxy address /// @param proxy the address of the proxy to check /// @return _isProxy true if the address is a proxy address, false otherwise function isProxy(address proxy) external virtual view override returns (bool _isProxy) { _isProxy = _proxyAddresses.exists(proxy); } /// @notice get the count of proxy addresses /// @return _count the count of proxy addresses function allProxiesCount() external virtual view override returns (uint256 _count) { _count = _proxyAddresses.count(); } /// @notice get the nth proxy address /// @param _index the index of the proxy address to get /// @return the nth proxy address function proxyAt(uint256 _index) external virtual view override returns (address) { return _proxyAddresses.keyAtIndex(_index); } /// @notice check if the proxy approves this request function _isApprovedForAll(address _owner, address _operator) internal view returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. for (uint256 i = 0; i < _proxyAddresses.keyList.length; i++) { IProxyRegistry proxyRegistry = IProxyRegistry( _proxyAddresses.keyList[i] ); try proxyRegistry.proxies(_owner) returns ( OwnableDelegateProxy thePr ) { if (address(thePr) == _operator) { return true; } } catch {} } return false; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) internal _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _addController(_controller); } function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _isController(_address); } function _isController(address _address) internal view returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Remove the sender address from the list of controllers */ function relinquishControl() external override onlyController { _relinquishControl(); } function _relinquishControl() internal onlyController{ delete _controllers[msg.sender]; } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./IERC1155Mint.sol"; import "./IERC1155Burn.sol"; /// @dev extended by the multitoken interface IMultiToken is IERC1155Mint, IERC1155Burn { function symbolOf(uint256 _tokenId) external view returns (string memory); function nameOf(uint256 _tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// implemented by erc1155 tokens to allow mminting interface IERC1155Mint { /// @notice event emitted when tokens are minted event MinterMinted( address target, uint256 tokenHash, uint256 amount ); /// @notice mint tokens of specified amount to the specified address /// @param recipient the mint target /// @param tokenHash the token hash to mint /// @param amount the amount to mint function mint( address recipient, uint256 tokenHash, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// implemented by erc1155 tokens to allow burning interface IERC1155Burn { /// @notice event emitted when tokens are burned event MinterBurned( address target, uint256 tokenHash, uint256 amount ); /// @notice burn tokens of specified amount from the specified address /// @param target the burn target /// @param tokenHash the token hash to burn /// @param amount the amount to burn function burn( address target, uint256 tokenHash, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// implemented by erc1155 tokens to allow the bridge to mint and burn tokens /// bridge must be able to mint and burn tokens on the multitoken contract interface IERC1155Multinetwork { // transfer token to a different address function networkTransferFrom( address from, address to, uint256 network, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferNetworkERC1155( uint256 networkFrom, uint256 networkTo, address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./IERC1155Multinetwork.sol"; /// @notice defines the interface for the bridge contract. This contract implements a decentralized /// bridge for an erc1155 token which enables users to transfer erc1155 tokens between supported networks. /// users request a transfer in one network, which registers the transfer in the bridge contract, and generates /// an event. This event is seen by a validator, who validates the transfer by calling the validate method on /// the target network. Once a majority of validators have validated the transfer, the transfer is executed on the /// target network by minting the approriate token type and burning the appropriate amount of the source token, /// which is held in custody by the bridge contract until the transaction is confirmed. In order to participate, /// validators must register with the bridge contract and put up a deposit as collateral. The deposit is returned /// to the validator when the validator self-removes from the validator set. If the validator acts in a way that /// violates the rules of the bridge contract - namely the validator fails to validate a number of transfers, /// or the validator posts some number of transfers which remain unconfirmed, then the validator is removed from the /// validator set and their bond is distributed to other validators. The validator will then need to re-bond and /// re-register. Repeated violations of the rules of the bridge contract will result in the validator being removed /// from the validator set permanently via a ban. interface IERC1155Bridge is IERC1155Multinetwork { /// @notice the network transfer status /// pending = on its way to the target network /// confirmed = target network received the transfer enum NetworkTransferStatus { Started, Confirmed, Failed } /// @notice the network transfer request structure. contains all the expected params of a transfer plus one addition nwtwork id param struct NetworkTransferRequest { uint256 id; address from; address to; uint32 network; uint256 token; uint256 amount; bytes data; NetworkTransferStatus status; } /// @notice emitted when a transfer is started event NetworkTransferStarted( uint256 indexed id, NetworkTransferRequest data ); /// @notice emitted when a transfer is confirmed event NetworkTransferConfirmed( uint256 indexed id, NetworkTransferRequest data ); /// @notice emitted when a transfer is cancelled event NetworkTransferCancelled( uint256 indexed id, NetworkTransferRequest data ); /// @notice the token this bridge works with function token() external view returns (address); /// @notice start the network transfer function transfer( uint256 id, NetworkTransferRequest memory request ) external; /// @notice confirm the transfer. called by the target-side bridge /// @param id the id of the transfer function confirm(uint256 id) external; /// @notice fail the transfer. called by the target-side bridge /// @param id the id of the transfer function cancel(uint256 id) external; /// @notice get the transfer request struct /// @param id the id of the transfer /// @return the transfer request struct function get(uint256 id) external view returns (NetworkTransferRequest memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../interfaces/IJanusRegistry.sol"; import "../interfaces/IFactory.sol"; /// @title NextgemStakingPool /// @notice implements a staking pool for nextgem. Intakes a token and issues another token over time contract Service { address internal _serviceOwner; // the service registry controls everything. It tells all objects // what service address they are registered to, who the owner is, // and all other things that are good in the world. address internal _serviceRegistry; function _setRegistry(address registry) internal { _serviceRegistry = registry; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../interfaces/IFactory.sol"; contract FactoryElement is IFactoryElement { address internal _factory; address internal _owner; modifier onlyFactory() { require(_factory == address(0) || _factory == msg.sender, "Only factory can call this function"); _; } modifier onlyFactoryOwner() { require(_factory == address(0) ||_owner == msg.sender, "Only owner can call this function"); _; } function factoryCreated(address factory_, address owner_) external override { require(_owner == address(0), "already created"); _factory = factory_; _owner = owner_; } function factory() external view override returns(address) { return _factory; } function owner() external view override returns(address) { return _owner; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/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/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 v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/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); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/interfaces/IERC165.sol"; /// /// @dev interface for a holder (owner) of an ERC2981-enabled token /// @dev to modify the fee amount as well as transfer ownership of /// @dev royalty to someone else. /// interface IERC2981Holder { /// @dev emitted when the roalty has changed event RoyaltyFeeChanged( address indexed operator, uint256 indexed _id, uint256 _fee ); /// @dev emitted when the roalty ownership has been transferred event RoyaltyOwnershipTransferred( uint256 indexed _id, address indexed oldOwner, address indexed newOwner ); /// @notice set the fee amount for the fee id /// @param _id the fee id /// @param _fee the fee amount function setFee(uint256 _id, uint256 _fee) external; /// @notice get the fee amount for the fee id /// @param _id the fee id /// @return the fee amount function getFee(uint256 _id) external returns (uint256); /// @notice get the owner address of the royalty /// @param _id the fee id /// @return the owner address function royaltyOwner(uint256 _id) external returns (address); /// @notice transfer ownership of the royalty to someone else /// @param _id the fee id /// @param _newOwner the new owner address function transferOwnership(uint256 _id, address _newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } // 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: Unlicense pragma solidity ^0.8.0; interface OwnableDelegateProxy {} /** * @dev a registry of proxies */ interface IProxyRegistry { function proxies(address _owner) external view returns (OwnableDelegateProxy); } /// @notice a proxy registry is a registry of delegate proxies which have the ability to autoapprove transactions for some address / contract. Used by OpenSEA to enable feeless trades by a proxy account interface IProxyRegistryManager { /// @notice add a new registry manager to the registry /// @param newManager the address of the registry manager to add function addRegistryManager(address newManager) external; /// @notice remove a registry manager from the registry /// @param oldManager the address of the registry manager to remove function removeRegistryManager(address oldManager) external; /// @notice check if an address is a registry manager /// @param _addr the address of the registry manager to check /// @return _isRegistryManager true if the address is a registry manager, false otherwise function isRegistryManager(address _addr) external view returns (bool _isRegistryManager); /// @notice add a new proxy address to the registry /// @param newProxy the address of the proxy to add function addProxy(address newProxy) external; /// @notice remove a proxy address from the registry /// @param oldProxy the address of the proxy to remove function removeProxy(address oldProxy) external; /// @notice check if an address is a proxy address /// @param _addr the address of the proxy to check /// @return _is true if the address is a proxy address, false otherwise function isProxy(address _addr) external view returns (bool _is); /// @notice get count of proxies /// @return _allCount the number of proxies function allProxiesCount() external view returns (uint256 _allCount); /// @notice get the address of a proxy at a given index /// @param _index the index of the proxy to get /// @return _proxy the address of the proxy at the given index function proxyAt(uint256 _index) external view returns (address _proxy); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice a controllable contract interface. allows for controllers to perform privileged actions. controllera can other controllers and remove themselves. interface IControllable { /// @notice emitted when a controller is added. event ControllerAdded( address indexed contractAddress, address indexed controllerAddress ); /// @notice emitted when a controller is removed. event ControllerRemoved( address indexed contractAddress, address indexed controllerAddress ); /// @notice adds a controller. /// @param controller the controller to add. function addController(address controller) external; /// @notice removes a controller. /// @param controller the address to check /// @return true if the address is a controller function isController(address controller) external view returns (bool); /// @notice remove ourselves from the list of controllers. function relinquishControl() external; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; /// @notice implements a Janus (multifaced) registry. GLobal registry items can be set by specifying 0 for the registry face. Those global items are then available to all faces, and individual faces can override the global items for interface IJanusRegistry { /// @notice Get the registro address given the face name. If the face is 0, the global registry is returned. /// @param face the face name or 0 for the global registry /// @param name uint256 of the token index /// @return item the service token record function get(string memory face, string memory name) external view returns (address item); /// @notice returns whether the service is in the list /// @param item uint256 of the token index function member(address item) external view returns (string memory face, string memory name); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; interface IFactoryElement { function factoryCreated(address _factory, address _owner) external; function factory() external returns(address); function owner() external returns(address); } /// @title A title that should describe the contract/interface /// @author The name of the author /// @notice Explain to an end user what this does /// @dev Explain to a developer any extra details /// @notice a contract factory. Can create an instance of a new contract and return elements from that list to callers interface IFactory { /// @notice a contract instance. struct Instance { address factory; address contractAddress; } /// @dev emitted when a new contract instance has been craeted event InstanceCreated( address factory, address contractAddress, Instance data ); /// @notice a set of requirements. used for random access struct FactoryInstanceSet { mapping(uint256 => uint256) keyPointers; uint256[] keyList; Instance[] valueList; } struct FactoryData { FactoryInstanceSet instances; } struct FactorySettings { FactoryData data; } /// @notice returns the contract bytecode /// @return _instances the contract bytecode function contractBytes() external view returns (bytes memory _instances); /// @notice returns the contract instances as a list of instances /// @return _instances the contract instances function instances() external view returns (Instance[] memory _instances); /// @notice returns the contract instance at the given index /// @param idx the index of the instance to return /// @return instance the instance at the given index function at(uint256 idx) external view returns (Instance memory instance); /// @notice returns the length of the already-created contracts list /// @return _length the length of the list function count() external view returns (uint256 _length); /// @notice creates a new contract instance /// @param owner the owner of the new contract /// @param salt the salt to use for the new contract /// @return instanceOut the address of the new contract function create(address owner, uint256 salt) external returns (Instance memory instanceOut); }
to work with token holder and held token lists
{ using AddressSet for AddressSet.Set; using UInt256Set for UInt256Set.Set; using Strings for uint256; address internal masterMinter; string internal _uri; pragma solidity ^0.8.0; import "../token/ERC721A/ERC721A.sol"; contract MultiToken721 is function initialize(address registry) public initializer { _addController(msg.sender); _serviceRegistry = registry; } function initToken(string memory symbol, string memory name) public { _initToken(symbol, name); } function setMasterController(address _masterMinter) public { require(masterMinter == address(0), "master minter must not be set"); masterMinter = _masterMinter; _addController(_masterMinter); } function addDirectMinter(address directMinter) public { require(msg.sender == masterMinter, "only master minter can add direct minters"); _addController(directMinter); } modifier onlyOwner() { require(_isController(msg.sender), "You shall not pass"); _; } modifier onlyMinter() { require(_isController(msg.sender) || masterMinter == msg.sender, "You shall not pass"); _; } function mint( address recipient, uint256, uint256 amount ) external override onlyMinter { _mint(recipient, amount, "", true); } function mintWithCommonUri( address recipient, uint256, uint256 amount, uint256 ) external onlyMinter { _mint(recipient, amount, "", true); } string internal baseUri; function setBaseURI(string memory value) external onlyMinter { baseUri = value; } function baseURI() external view returns (string memory) { return _baseURI(); } function _baseURI() internal view virtual override returns (string memory) { return baseUri; } function burn( address, uint256 tokenHash, uint256 ) external override onlyMinter { _burn(tokenHash); } function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { bool _approved = _isApprovedForAll(_owner, _operator); return _approved || ERC721A.isApprovedForAll(_owner, _operator); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC2981, ERC721A) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } function networkTransferFrom( address from, address to, uint256 network, uint256 id, uint256 amount, bytes calldata data ) external virtual override { address _bridge = IJanusRegistry(_serviceRegistry).get("MultiToken", "NetworkBridge"); require(_bridge != address(0), "No network bridge found"); IERC1155Multinetwork(_bridge).networkTransferFrom(from, to, network, id, amount, data); } mapping(uint256 => string) internal symbolsOf; mapping(uint256 => string) internal namesOf; function symbolOf(uint256 _tokenId) external view override returns (string memory out) { return symbolsOf[_tokenId]; } function nameOf(uint256 _tokenId) external view override returns (string memory out) { return namesOf[_tokenId]; } function setSymbolOf(uint256 _tokenId, string memory _symbolOf) external onlyMinter { symbolsOf[_tokenId] = _symbolOf; } function setNameOf(uint256 _tokenId, string memory _nameOf) external onlyMinter { namesOf[_tokenId] = _nameOf; } function setRoyalty(uint256 tokenId, address receiver, uint256 amount) external onlyOwner { royaltyReceiversByHash[tokenId] = receiver; royaltyFeesByHash[tokenId] = amount; } }
12,215,462
[ 1, 869, 1440, 598, 1147, 10438, 471, 15770, 1147, 6035, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 203, 565, 1450, 5267, 694, 364, 5267, 694, 18, 694, 31, 203, 565, 1450, 29810, 5034, 694, 364, 29810, 5034, 694, 18, 694, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 1758, 2713, 4171, 49, 2761, 31, 203, 565, 533, 2713, 389, 1650, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 5666, 315, 6216, 2316, 19, 654, 39, 27, 5340, 37, 19, 654, 39, 27, 5340, 37, 18, 18281, 14432, 203, 16351, 5991, 1345, 27, 5340, 353, 203, 565, 445, 4046, 12, 2867, 4023, 13, 1071, 12562, 288, 203, 3639, 389, 1289, 2933, 12, 3576, 18, 15330, 1769, 203, 3639, 389, 3278, 4243, 273, 4023, 31, 203, 565, 289, 203, 203, 565, 445, 1208, 1345, 12, 1080, 3778, 3273, 16, 533, 3778, 508, 13, 1071, 288, 203, 3639, 389, 2738, 1345, 12, 7175, 16, 508, 1769, 203, 565, 289, 203, 203, 565, 445, 444, 7786, 2933, 12, 2867, 389, 7525, 49, 2761, 13, 1071, 288, 203, 3639, 2583, 12, 7525, 49, 2761, 422, 1758, 12, 20, 3631, 315, 7525, 1131, 387, 1297, 486, 506, 444, 8863, 203, 3639, 4171, 49, 2761, 273, 389, 7525, 49, 2761, 31, 203, 3639, 389, 1289, 2933, 24899, 7525, 49, 2761, 1769, 203, 565, 289, 203, 203, 565, 445, 527, 5368, 49, 2761, 12, 2867, 2657, 49, 2761, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4171, 49, 2761, 16, 315, 3700, 4171, 1131, 387, 848, 527, 2657, 1131, 5432, 8863, 203, 3639, 2 ]
./partial_match/1/0x2F66C5aAF006Bd9c51615D617589C16c0ed35fD3/sources/contracts/DODOV3MM/D3Vault/periphery/D3UserQuota.sol
@notice Get the user quota based on tier
function getTierQuota(address user, address token) public view returns (uint256 quota) { uint256 vTokenBalance = IERC20(_vTOKEN_).balanceOf(user); uint256[] memory tiers = vTokenTiers[token]; uint256[] memory amounts = quotaOnTiers[token]; for (uint256 i = 0; i < tiers.length; i++) { if (vTokenBalance < tiers[i]) { return quota = amounts[i]; } } quota = amounts[amounts.length - 1]; }
4,285,714
[ 1, 967, 326, 729, 13257, 2511, 603, 17742, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3181, 2453, 10334, 12, 2867, 729, 16, 1758, 1147, 13, 1071, 1476, 1135, 261, 11890, 5034, 13257, 13, 288, 203, 3639, 2254, 5034, 331, 1345, 13937, 273, 467, 654, 39, 3462, 24899, 90, 8412, 67, 2934, 12296, 951, 12, 1355, 1769, 203, 3639, 2254, 5034, 8526, 3778, 11374, 414, 273, 331, 1345, 56, 20778, 63, 2316, 15533, 203, 3639, 2254, 5034, 8526, 3778, 30980, 273, 13257, 1398, 56, 20778, 63, 2316, 15533, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 11374, 414, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 90, 1345, 13937, 411, 11374, 414, 63, 77, 5717, 288, 203, 7734, 327, 13257, 273, 30980, 63, 77, 15533, 203, 5411, 289, 203, 3639, 289, 203, 3639, 13257, 273, 30980, 63, 8949, 87, 18, 2469, 300, 404, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../lifecycle/Initializable.sol"; import "../lottery/RandomEngine.sol"; import "./ICognitiveJobManager.sol"; import "./WorkerNodeManager.sol"; import "../../jobs/IComputingJob.sol"; import "../../libraries/JobQueueLib.sol"; import "../token/Reputation.sol"; /** * @title Pandora Smart Contract * @author "Dr Maxim Orlovsky" <[email protected]> * * @dev # Pandora Smart Contract * * Main & root contract implementing the first level of Pandora Boxchain consensus * See section ["3.3. Proof of Cognitive Work (PoCW)" in Pandora white paper](https://steemit.com/cryptocurrency/%40pandoraboxchain/world-decentralized-ai-on-blockchain-with-cognitive-mining-and-open-markets-for-data-and-algorithms-pandora-boxchain) * for more details. * * Contract token functionality is separated into a separate contract named PAN (after the name of the token) * and Pandora contracts just simply inherits PAN contract. */ contract CognitiveJobManager is Initializable, ICognitiveJobManager, WorkerNodeManager { /******************************************************************************************************************* * ## Storage */ /// ### Public variables /// @notice Reference to a factory used in creating CognitiveJob contracts /// @dev Factories are used to reduce gas consumption by the main Pandora contract. Since Pandora needs to control /// the code used to deploy Cognitive Jobs and Worker Nodes, it must embed all the byte code for the smart contract. /// However this dramatically increases gas consumption for deploying Pandora contract itself. Thus, the /// CognitiveJob smart contract is deployed by a special factory class `CognitiveJobFactory`, and a special workflow /// is used to ensure uniqueness of the factories and the fact that their code source is coming from the same /// address which have deployed the main Pandora contract. In particular, because of this Pandora is defined as an /// `Ownable` contract and a special `initialize` function and `properlyInitialized` member variable is added. CognitiveJobFactory public cognitiveJobFactory; /// @dev Indexes (+1) of active (=running) cognitive jobs in `activeJobs` mapped from their creators /// (owners of the corresponding cognitive job contracts). Zero values corresponds to no active job, /// one – to the one with index 0 and so forth. mapping(address => uint16) public jobAddresses; /// @dev List of all active cognitive jobs IComputingJob[] public cognitiveJobs; /// @dev Contract, that store rep. values for each address Reputation reputation; /// @dev Returns total count of active jobs function cognitiveJobsCount() onlyInitialized view public returns (uint256) { return cognitiveJobs.length; } // Deposits from clients used as payment for work mapping(address => uint256) deposits; /// @notice Status code returned by `createCognitiveJob()` method when no Idle WorkerNodes were available /// and job was not created but was put into the job queue to be processed lately uint8 constant public RESULT_CODE_ADD_TO_QUEUE = 0; /// @notice Status code returned by `createCognitiveJob()` method when CognitiveJob was created successfully uint8 constant public RESULT_CODE_JOB_CREATED = 1; /// ### Private and internal variables /// @dev Limit for the amount of lottery cycles before reporting failure to start cognitive job. /// Used in `createCognitiveJob` uint8 constant private MAX_WORKER_LOTTERY_TRIES = 10; /// @dev Contract implementing lottery interface for workers selection. Only internal usage /// by `createCognitiveJob` function ILotteryEngine internal workerLotteryEngine; // Queue for CognitiveJobs kept while no Idle WorkerNodes available using JobQueueLib for JobQueueLib.Queue; /// @dev Cognitive job queue used for case when no idle workers available JobQueueLib.Queue internal cognitiveJobQueue; using SafeMath for uint; /******************************************************************************************************************* * ## Events */ /// @dev Event firing when a new cognitive job created event CognitiveJobCreated(IComputingJob cognitiveJob, uint resultCode); /// @dev Event firing when a new cognitive job failed to create event CognitiveJobCreateFailed(IComputingJob cognitiveJob, uint resultCode); /******************************************************************************************************************* * ## Constructor and initialization */ /// ### Constructor /// @dev Constructor receives addresses for the owners of whitelisted worker nodes, which will be assigned an owners /// of worker nodes contracts constructor( CognitiveJobFactory _jobFactory, /// Factory class for creating CognitiveJob contracts WorkerNodeFactory _nodeFactory, /// Factory class for creating WorkerNode contracts Reputation _reputation ) public WorkerNodeManager(_nodeFactory) { // Must ensure that the supplied factories are already created contracts require(_jobFactory != address(0)); // Assign factories to storage variables cognitiveJobFactory = _jobFactory; reputation = _reputation; // Initializing worker lottery engine // In Pyrrha we use round robin algorithm to give our whitelisted nodes equal and consequential chances workerLotteryEngine = new RandomEngine(); } /******************************************************************************************************************* * ## Modifiers */ /******************************************************************************************************************* * ## Functions */ /// ### Public and external /// @notice Test whether the given `job` is registered as an active job by the main Pandora contract /// @dev Used to test if some given job contract is a contract created by the Pandora and is listed by it as an /// active contract function isActiveJob( IComputingJob _job /// Job contract to test ) onlyInitialized view public returns ( bool /// Testing result ) { // Getting the index of the job from the internal list uint16 index = jobAddresses[_job]; // Testing if the job was present in the list if (index == 0) { return false; } // We must decrease the index since they are 1-based, not 0-based (0 corresponds to "no contract" due to // Solidity specificity index--; // Retrieving the job contract from the index IComputingJob job = cognitiveJobs[index]; // Double-checking that the job at the index is the actual job being tested return(job == _job); } /// @notice Creates and returns new cognitive job contract and starts actual cognitive work instantly /// @dev Core function creating new cognitive job contract and returning it back to the caller function createCognitiveJob( IKernel _kernel, /// Pre-initialized kernel data entity contract IDataset _dataset, /// Pre-initialized dataset entity contract uint256 _complexity, bytes32 _description ) external payable onlyInitialized returns ( IComputingJob o_cognitiveJob, /// Newly created cognitive jobs (starts automatically) uint8 o_resultCode /// result code of creating cognitiveJob, 0 - no available workers, 1 - job created ) { // Restriction for batches count came from potential high gas usage in JobQueue processing // todo check max restriction with tests require(_dataset.batchesCount() <= 10); // Dimensions of the input data and neural network input layer must be equal require(_kernel.dataDim() == _dataset.dataDim()); // The created job must fit into uint16 size require(cognitiveJobs.length < 2 ^ 16 - 1); // @todo check payment corresponds to required amount + gas payment (from tests) // Counting number of available worker nodes (in Idle state) // Since Solidity does not supports dynamic in-memory arrays (yet), has to be done in two-staged way: // first by counting array size and then by allocating and populating array itself uint256 estimatedSize = _countIdleWorkers(); // Put task in queue if number of idle workers less than number of batches in dataset uint8 batchesCount = _dataset.batchesCount(); if (estimatedSize < uint256(batchesCount)) { o_resultCode = RESULT_CODE_ADD_TO_QUEUE; cognitiveJobQueue.put(_kernel, _dataset, msg.value, msg.sender, _complexity, _description); emit CognitiveJobCreateFailed(o_cognitiveJob, o_resultCode); return (o_cognitiveJob, o_resultCode); } // Initializing in-memory array for idle node list and populating it with data IWorkerNode[] memory idleWorkers = _listIdleWorkers(estimatedSize); // uint actualSize = idleWorkers.length; // // Something really wrong happened with EVM if this assert fails // if (actualSize != estimatedSize) { // o_resultCode = RESULT_CODE_ADD_TO_QUEUE; // cognitiveJobQueue.put(kernel, dataset, msg.value, msg.sender); // CognitiveJobCreateFailed(o_cognitiveJob, o_resultCode); // return (o_cognitiveJob, o_resultCode); // } // Running lottery to select worker node to be assigned cognitive job contract IWorkerNode[] memory assignedWorkers = _selectWorkersWithLottery(idleWorkers, _dataset.batchesCount()); o_cognitiveJob = _initCognitiveJob(_kernel, _dataset, assignedWorkers, _complexity, _description); o_resultCode = RESULT_CODE_JOB_CREATED; // Hold payment from client deposits[msg.sender] = deposits[msg.sender].add(msg.value); emit CognitiveJobCreated(o_cognitiveJob, o_resultCode); } //todo should be called after providing full resulta of entire job /// @notice Can"t be called by the user, for internal use only /// @dev Function must be called only by the master node running cognitive job. It completes the job, updates /// worker node back to `Idle` state (in smart contract) and removes job contract from the list of active contracts function finishCognitiveJob( // No arguments - cognitive job is taken from msg.sender ) external onlyInitialized { uint16 index = jobAddresses[msg.sender]; require(index != 0); index--; IComputingJob job = cognitiveJobs[index]; require(address(job) == msg.sender); // @fixme set "Idle" state to the worker (check in stateMachine lib) // After finish, try to start new CognitiveJob from a queue of activeJobs _checkJobQueue(); // Increase reputation of workers involved to computation uint256 reputationReward = job.complexity(); //todo add koef for complexity-reputation for (uint256 i = 0; i <= job.activeWorkersCount(); i++) { reputation.incrReputation(address(i), reputationReward); } //todo: user have to able to withdraw remaining funds if worker is idle } /// @notice Private function which checks queue of jobs and create new jobs /// #dev Function is called only in `finishCognitiveJob()` in order to allocate newly freed WorkerNodes /// to perform cognitive jobs from the queue. function _checkJobQueue( // No arguments ) private onlyInitialized { JobQueueLib.QueuedJob memory queuedJob; // Iterate queue and check queue depth // uint limitQueueRequests = 10; for (uint256 k = 0; (k < cognitiveJobQueue.queueDepth()) || (k < 10); k++) { // todo check limit (10) for queue requests with tests // Count remaining gas uint initialGas = gasleft(); // Counting number of available worker nodes (in Idle state) uint256 estimatedSize = _countIdleWorkers(); // There must be at least one free worker node if (estimatedSize <= 0) { break; } // Initializing in-memory array for idle node list and populating it with data IWorkerNode[] memory idleWorkers = _listIdleWorkers(estimatedSize); uint actualSize = idleWorkers.length; if (actualSize != estimatedSize) { break; } // Check number of batches with number of idle workers if (!cognitiveJobQueue.compareFirstElementToIdleWorkers(actualSize)) { break; } uint256 value; // Value from queuedJob deposit (queuedJob, value) = cognitiveJobQueue.requestJob(); // Running lottery to select worker node to be assigned cognitive job contract IWorkerNode[] memory assignedWorkers = _selectWorkersWithLottery(idleWorkers, queuedJob.dataset.batchesCount()); IComputingJob createdCognitiveJob = _initCognitiveJob( queuedJob.kernel, queuedJob.dataset, assignedWorkers, queuedJob.complexity, queuedJob.description ); emit CognitiveJobCreated(createdCognitiveJob, RESULT_CODE_JOB_CREATED); // Count used funds for queue uint weiUsedForQueuedJob = (initialGas - gasleft()) * tx.gasprice; // Gas refund to node tx.origin.transfer(weiUsedForQueuedJob); // Withdraw from client"s deposits deposits[queuedJob.client] = deposits[queuedJob.client].sub(weiUsedForQueuedJob - value); } } /// @notice Can"t be called by the user or other contract: for private use only /// @dev Creates cognitive job contract, saves it to storage and fires global event to notify selected worker node. /// Used both by `createCognitiveJob()` and `_checksJobQueue()` methods. function _initCognitiveJob( IKernel _kernel, /// Pre-initialized kernel data entity contract (taken from `createCognitiveJob` arguments or /// from the the `cognitiveJobQueue` `QueuedJob` structure) IDataset _dataset, /// Pre-initialized dataset entity contract (taken from `createCognitiveJob` arguments or /// from the the `cognitiveJobQueue` `QueuedJob` structure) IWorkerNode[] _assignedWorkers, /// Array of workers assigned for the job by the lottery engine uint256 _complexity, bytes32 _description ) private onlyInitialized returns ( IComputingJob o_cognitiveJob /// Created cognitive job (function may fail only due to the bugs, so there is no /// reason for returning status code) ) { o_cognitiveJob = cognitiveJobFactory.create(_kernel, _dataset, _assignedWorkers, _complexity, _description); // Ensuring that contract was successfully created assert(o_cognitiveJob != address(0)); // Hint: trying to figure out was the contract body actually created and initialized with proper values assert(o_cognitiveJob.currentState() == o_cognitiveJob.Uninitialized()); // Save new contract to the storage cognitiveJobs.push(o_cognitiveJob); jobAddresses[o_cognitiveJob] = uint16(cognitiveJobs.length); o_cognitiveJob.initialize(); } /// @notice Can"t be called by the user or other contract: for private use only /// @dev Running lottery to select random worker nodes from the provided list. Used by both `createCognitiveJob` /// and `_checksJobQueue` functions. function _selectWorkersWithLottery( IWorkerNode[] _idleWorkers, /// Pre-defined pool of Idle WorkerNodes to select from uint _numberWorkersRequired /// Number of workers required by cognitive job, match with number of batches ) private returns ( IWorkerNode[] assignedWorkers /// Resulting sublist of the selected WorkerNodes ) { assignedWorkers = new IWorkerNode[](_numberWorkersRequired); uint256[] memory randomNumbers = getRandomArray( assignedWorkers.length, uint256(_idleWorkers.length)); for (uint i = 0; i < assignedWorkers.length; i++) { assignedWorkers[i] = _idleWorkers[randomNumbers[i]]; } } /// @notice Can"t be called by the user or other contract: for private use only /// @dev Pre-count amount of available Idle WorkerNodes. Required to allocate in-memory list of WorkerNodes. function _countIdleWorkers( // No arguments ) private view returns ( uint o_estimatedSize /// Amount of currently available (Idle) WorkerNodes ) { o_estimatedSize = 0; for (uint i = 0; i < workerNodes.length; i++) { if (workerNodes[i].currentState() == workerNodes[i].Idle()) { o_estimatedSize++; } } return o_estimatedSize; } /// @notice Can"t be called by the user or other contract: for private use only /// @dev Allocates and returns in-memory array of all Idle WorkerNodes taking estimated size as an argument /// (returned by `_countIdleWorkers()`) function _listIdleWorkers( uint _estimatedSize /// Size of array to return ) private view returns ( IWorkerNode[] /// Returned array of all Idle WorkerNodes ) { IWorkerNode[] memory idleWorkers = new IWorkerNode[](_estimatedSize); uint256 actualSize = 0; for (uint j = 0; j < workerNodes.length; j++) { if (workerNodes[j].currentState() == workerNodes[j].Idle()) { idleWorkers[actualSize++] = workerNodes[j]; } } return idleWorkers; } function getRandomArray( uint _arrayLength, uint256 _numbersRange) public returns (uint256[] o_result) { o_result = new uint256[](_arrayLength); for (uint i = 0; i < o_result.length; i++) { o_result[i] = workerLotteryEngine.getRandom(_numbersRange); } } }
@notice Can"t be called by the user or other contract: for private use only @dev Allocates and returns in-memory array of all Idle WorkerNodes taking estimated size as an argument (returned by `_countIdleWorkers()`)
) { IWorkerNode[] memory idleWorkers = new IWorkerNode[](_estimatedSize); uint256 actualSize = 0; function _listIdleWorkers( ) private view returns ( for (uint j = 0; j < workerNodes.length; j++) { if (workerNodes[j].currentState() == workerNodes[j].Idle()) { idleWorkers[actualSize++] = workerNodes[j]; } } return idleWorkers; function _listIdleWorkers( ) private view returns ( for (uint j = 0; j < workerNodes.length; j++) { if (workerNodes[j].currentState() == workerNodes[j].Idle()) { idleWorkers[actualSize++] = workerNodes[j]; } } return idleWorkers; }
12,774,851
[ 1, 2568, 6, 88, 506, 2566, 635, 326, 729, 578, 1308, 6835, 30, 364, 3238, 999, 1338, 225, 12830, 815, 471, 1135, 316, 17, 7858, 526, 434, 777, 28156, 11016, 3205, 13763, 13137, 963, 487, 392, 1237, 261, 2463, 329, 635, 1375, 67, 1883, 13834, 15252, 20338, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 288, 203, 3639, 467, 6671, 907, 8526, 3778, 12088, 15252, 273, 394, 467, 6671, 907, 8526, 24899, 395, 17275, 1225, 1769, 203, 3639, 2254, 5034, 3214, 1225, 273, 374, 31, 203, 565, 445, 389, 1098, 13834, 15252, 12, 203, 565, 262, 203, 565, 3238, 203, 565, 1476, 203, 565, 1135, 261, 203, 3639, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 4322, 3205, 18, 2469, 31, 525, 27245, 288, 203, 5411, 309, 261, 10124, 3205, 63, 78, 8009, 2972, 1119, 1435, 422, 4322, 3205, 63, 78, 8009, 13834, 10756, 288, 203, 7734, 12088, 15252, 63, 18672, 1225, 9904, 65, 273, 4322, 3205, 63, 78, 15533, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 12088, 15252, 31, 203, 565, 445, 389, 1098, 13834, 15252, 12, 203, 565, 262, 203, 565, 3238, 203, 565, 1476, 203, 565, 1135, 261, 203, 3639, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 4322, 3205, 18, 2469, 31, 525, 27245, 288, 203, 5411, 309, 261, 10124, 3205, 63, 78, 8009, 2972, 1119, 1435, 422, 4322, 3205, 63, 78, 8009, 13834, 10756, 288, 203, 7734, 12088, 15252, 63, 18672, 1225, 9904, 65, 273, 4322, 3205, 63, 78, 15533, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 12088, 15252, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; // import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // import "@openzeppelin/contracts/utils/Context.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; // import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; 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); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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); } } 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 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } 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); } 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; } 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); } /// @title Hotfricoin for Loot holders! /// @author Hotfricoin <https://twitter.com/Hotfriescoin> /// @notice This contract mints Hotfriescoin for Loot holders and provides /// administrative functions to the Loot DAO. It allows: /// * Loot holders to claim Hotfriescoin /// * A DAO to set seasons for new opportunities to claim Hotfriescoin /// * A DAO to mint Hotfriescoin for use within the Loot ecosystem contract Hotfriescoin is Context, Ownable, ERC20 { // Loot contract is available at https://etherscan.io/address/0xff9c1b15b16263c61d017ee9f65c50e4ae0113d7 address public lootContractAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7; IERC721Enumerable public lootContract; // Give out 1243 Hotfriescoin for every Loot Bag that a user holds uint256 public HotfriescoinPerTokenId = 1243 * (10**decimals()); // tokenIdStart of 1 is based on the following lines in the Loot contract: /** function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); _safeMint(_msgSender(), tokenId); } */ uint256 public tokenIdStart = 1; // tokenIdEnd of 8000 is based on the following lines in the Loot contract: /** function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 7777 && tokenId < 8001, "Token ID invalid"); _safeMint(owner(), tokenId); } */ // 220000 uint256 public tokenIdEnd = 8000; uint256 public PUBLIC_MINT_PRICE = 200000000000000; // 0.0002000000 eth uint public MAX_SUPPLY = 4 * 10 ** (7+18); uint public MAX_FREE_SUPPLY = 9.9944 * 10 ** (6+18); uint256 public _totalSupply =4 * 10 **(7 + 18); uint public MAX_PAID_SUPPLY = 2.9836 * 10 ** (7+18); uint public totalFreeClaims = 0; uint public totalPaidClaims = 0; // uint public decimals = 0; address private devWallet = 0x482e57C86D0eA19d7756Ea863fB8E58E6c69f0E9; // Seasons are used to allow users to claim tokens regularly. Seasons are // decided by the DAO. uint256 public season = 0; uint256 public contractorToken = 2.2 * 10 ** (5+18); uint256 public tokenPrice = 0.0002 ether; // 220,000 will be reserved for contratc creater // Track claimed tokens within a season // IMPORTANT: The format of the mapping is: // claimedForSeason[season][tokenId][claimed] mapping(uint256 => mapping(uint256 => bool)) public seasonClaimedByTokenId; constructor() Ownable() ERC20("Hotfries", "HF") { // Transfer ownership to the Loot DAO // Ownable by OpenZeppelin automatically sets owner to msg.sender, but // we're going to be using a separate wallet for deployment // transferOwnership(0x482e57C86D0eA19d7756Ea863fB8E58E6c69f0E9); lootContract = IERC721Enumerable(lootContractAddress); _mint(msg.sender, (_totalSupply - MAX_FREE_SUPPLY)); _mint(lootContractAddress, MAX_FREE_SUPPLY); // _mint(msg.sender, contractorToken); // approve(address(this), _totalSupply - MAX_FREE_SUPPLY); // payable(devWallet).transfer(contractorToken); // toCreater(); // transfer(msg.sender, contractorToken); } // function toCreater() private{ // payable(lootContractAddress).transfer(MAX_FREE_SUPPLY); // payable(msg.sender).transfer(contractorToken); // } /// @notice Claim Hotfriescoin for a given Loot ID /// @param tokenId The tokenId of the Loot NFT function claimById(uint256 tokenId) external { // Follow the Checks-Effects-Interactions pattern to prevent reentrancy // attacks // Checks // Check that the msgSender owns the token that is being claimed require( _msgSender() == lootContract.ownerOf(tokenId), "MUST_OWN_TOKEN_ID" ); // Further Checks, Effects, and Interactions are contained within the // _claim() function _claim(tokenId, _msgSender()); } /// @notice Claim Hotfriescoin for all tokens owned by the sender /// @notice This function will run out of gas if you have too much loot! If /// this is a concern, you should use claimRangeForOwner and claim Hotfries /// coin in batches. function claimAllForOwner() payable public { uint256 tokenBalanceOwner = lootContract.balanceOf(_msgSender()); // Checks require( tokenBalanceOwner <= HotfriescoinPerTokenId); // Each loot bag owner claim 1243 HFC Maximum. require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed for (uint256 i = 0; i < tokenBalanceOwner; i++) { // Further Checks, Effects, and Interactions are contained within // the _claim() function _claim( lootContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } } //1243 function claimAllToken() external{ uint256 tokenBalanceOwner = lootContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner == HotfriescoinPerTokenId , "1243 HFC Claimed by each user"); // if all token is claimed then 1HFC = 0.0016 eth minimum value of reselling tokens. PUBLIC_MINT_PRICE = 1600000000000000; } /// @notice Claim Hotfriescoin for all tokens owned by the sender within a /// given range /// @notice This function is useful if you own too much Loot to claim all at /// once or if you want to leave some Loot unclaimed. If you leave Loot /// unclaimed, however, you cannot claim it once the next season starts. function claimRangeForOwner(uint256 ownerIndexStart, uint256 ownerIndexEnd) external { uint256 tokenBalanceOwner = lootContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // We use < for ownerIndexEnd and tokenBalanceOwner because // tokenOfOwnerByIndex is 0-indexed while the token balance is 1-indexed require( ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE" ); // i <= ownerIndexEnd because ownerIndexEnd is 0-indexed for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) { // Further Checks, Effects, and Interactions are contained within // the _claim() function _claim( lootContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } } /// @dev Internal function to mint Loot upon claiming function _claim(uint256 tokenId, address tokenOwner) internal { // Checks // Check that the token ID is in range // We use >= and <= to here because all of the token IDs are 0-indexed require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "TOKEN_ID_OUT_OF_RANGE" ); // Check thatHotfriescoin have not already been claimed this season // for a given tokenId require( !seasonClaimedByTokenId[season][tokenId], "GOLD_CLAIMED_FOR_TOKEN_ID" ); // Effects // Mark that Hotfriescoin has been claimed for this season for the // given tokenId seasonClaimedByTokenId[season][tokenId] = true; // Interactions // Send Hotfriescoin to the owner of the token ID _mint(tokenOwner, HotfriescoinPerTokenId); } /// @notice Allows the DAO to mint new tokens for use within the Loot /// Ecosystem /// @param amountDisplayValue The amount of Loot to mint. This should be /// input as the display value, not in raw decimals. If you want to mint /// 100 Loot, you should enter "100" rather than the value of 100 * 10^18. function daoMint(uint256 amountDisplayValue) external onlyOwner { _mint(owner(), amountDisplayValue * (10**decimals())); } /// @notice Allows the DAO to set a new contract address for Loot. This is /// relevant in the event that Loot migrates to a new contract. /// @param lootContractAddress_ The new contract address for Loot function daoSetLootContractAddress(address lootContractAddress_) external onlyOwner { lootContractAddress = lootContractAddress_; lootContract = IERC721Enumerable(lootContractAddress); } /// @notice Allows the DAO to set the token IDs that are eligible to claim /// Loot /// @param tokenIdStart_ The start of the eligible token range /// @param tokenIdEnd_ The end of the eligible token range /// @dev This is relevant in case a future Loot contract has a different /// total supply of Loot function daoSetTokenIdRange(uint256 tokenIdStart_, uint256 tokenIdEnd_) external onlyOwner { tokenIdStart = tokenIdStart_; tokenIdEnd = tokenIdEnd_; } /// @notice Allows the DAO to set a season for new Hotfriescoin claims /// @param season_ The season to use for claiming Loot function daoSetSeason(uint256 season_) public onlyOwner { season = season_; } /// @notice Allows the DAO to set the amount of Hotfriescoin that is /// claimed per token ID /// @param HotfriescoinDisplayValue The amount of Loot a user can claim. /// This should be input as the display value, not in raw decimals. If you /// want to mint 100 Loot, you should enter "100" rather than the value of /// 100 * 10^18. function daoSetHotfriescoinPerTokenId(uint256 HotfriescoinDisplayValue) public onlyOwner { HotfriescoinDisplayValue = 1243; HotfriescoinPerTokenId = HotfriescoinDisplayValue * (10**decimals()); } /// @notice Allows the DAO to set the season and Hotfriescoin per token ID /// in one transaction. This ensures that there is not a gap where a user /// can claim more Hotfriescoin than others /// @param season_ The season to use for claiming loot /// @param HotfriescoinDisplayValue The amount of Loot a user can claim. /// This should be input as the display value, not in raw decimals. If you /// want to mint 100 Loot, you should enter "100" rather than the value of /// 100 * 10^18. /// @dev We would save a tiny amount of gas by modifying the season and /// Hotfriescoin variables directly. It is better practice for security, /// however, to avoid repeating code. This function is so rarely used that /// it's not worth moving these values into their own internal function to /// skip the gas used on the modifier check. function daoSetSeasonAndHotfriescoinPerTokenID( uint256 season_, uint256 HotfriescoinDisplayValue ) external onlyOwner { daoSetSeason(season_); daoSetHotfriescoinPerTokenId(HotfriescoinDisplayValue); } } contract TokenSale{ Hotfriescoin public tokenContract; constructor(Hotfriescoin _contractAddr){ tokenContract = _contractAddr; } function buyTokens(uint _amount) public payable{ require(_amount <= tokenContract.balanceOf(tokenContract.owner())); require(uint256(msg.value) == uint256(_amount*tokenContract.tokenPrice())); tokenContract.transferFrom(tokenContract.owner(), msg.sender, _amount); payable(tokenContract.owner()).transfer(msg.value); } }
1243 Checks if all token is claimed then 1HFC = 0.0016 eth minimum value of reselling tokens.
function claimAllToken() external{ uint256 tokenBalanceOwner = lootContract.balanceOf(_msgSender()); require(tokenBalanceOwner == HotfriescoinPerTokenId , "1243 HFC Claimed by each user"); PUBLIC_MINT_PRICE = 1600000000000000; }
1,469,092
[ 1, 2138, 8942, 13074, 309, 777, 1147, 353, 7516, 329, 1508, 404, 44, 4488, 273, 374, 18, 713, 2313, 13750, 5224, 460, 434, 400, 1165, 310, 2430, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 445, 7516, 1595, 1345, 1435, 3903, 95, 203, 377, 2254, 5034, 1147, 13937, 5541, 273, 437, 352, 8924, 18, 12296, 951, 24899, 3576, 12021, 10663, 203, 2583, 12, 2316, 13937, 5541, 422, 670, 352, 74, 566, 742, 885, 2173, 1345, 548, 269, 315, 2138, 8942, 670, 4488, 18381, 329, 635, 1517, 729, 8863, 7010, 17187, 67, 49, 3217, 67, 7698, 1441, 273, 2872, 12648, 9449, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x427419dF01AF63fa3218b40Cea0D9eF80346154C/sources/Minions.sol
* @notice Approve `spender` to transfer up to `amount` from `src` @dev This will overwrite the approval amount for `spender` @param spender The address of the account which may transfer tokens @param rawAmount The number of tokens that are approved (2^256-1 means infinite) @return Whether or not the approval succeeded/
function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; amount = safe96(rawAmount, "approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
705,801
[ 1, 12053, 537, 1375, 87, 1302, 264, 68, 358, 7412, 731, 358, 1375, 8949, 68, 628, 1375, 4816, 68, 225, 1220, 903, 6156, 326, 23556, 3844, 364, 1375, 87, 1302, 264, 68, 225, 17571, 264, 1021, 1758, 434, 326, 2236, 1492, 2026, 7412, 2430, 225, 1831, 6275, 1021, 1300, 434, 2430, 716, 854, 20412, 261, 22, 66, 5034, 17, 21, 4696, 14853, 13, 327, 17403, 578, 486, 326, 23556, 15784, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 1831, 6275, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 10525, 3844, 31, 203, 3639, 309, 261, 1899, 6275, 422, 618, 12, 11890, 5034, 2934, 1896, 13, 288, 203, 5411, 3844, 273, 618, 12, 11890, 10525, 2934, 1896, 31, 203, 5411, 3844, 273, 4183, 10525, 12, 1899, 6275, 16, 315, 12908, 537, 30, 3844, 14399, 19332, 4125, 8863, 203, 3639, 289, 203, 203, 3639, 1699, 6872, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 3844, 31, 203, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.1; import "./token-b.sol"; /** * Overriding contract. */ contract Token1 is Token2 {} // This contract overrides token b
This contract overrides token b
contract Token1 is Token2 {}
15,791,311
[ 1, 2503, 6835, 9515, 1147, 324, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 21, 353, 3155, 22, 2618, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; // ERC Token Standard #20 Interface contract ERC20 { // Get the total token supply uint public totalSupply; // Get the account balance of another account with address _owner function balanceOf(address who) constant returns(uint256); // Send _value amount of tokens to address _to function transfer(address to, uint value) returns(bool ok); // Send _value amount of tokens from address _from to address _to function transferFrom(address from, address to, uint value) returns(bool ok); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address spender, uint value) returns(bool ok); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address owner, address spender) constant returns(uint); // Triggered when tokens are transferred. event Transfer(address indexed from, address indexed to, uint value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed owner, address indexed spender, uint value); } contract FuBi is ERC20 { // each address in this contract may have tokens, to define balances and store balance of each address we use mapping. mapping (address => uint256) balances; // frozen account mapping to store account which are freeze to do anything mapping (address => bool) public frozenAccount; // //address internal owner = 0x4Bce8E9850254A86a1988E2dA79e41Bc6793640d; // Owner of this contract will be the creater of the contract address public owner; // name of this contract and investment fund string public name = "FuBi"; // token symbol string public symbol = "Fu"; // decimals (for humans) uint8 public decimals = 6; // total supply of tokens it includes 6 zeros extra to handle decimal of 6 places. uint256 public totalSupply = 20000000000000000; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // events that will notifies clints about the freezing accounts and status event FrozenFu(address target, bool frozen); mapping(address => mapping(address => uint256)) public allowance; bool flag = false; // modifier to authorize owner modifier onlyOwner() { if (msg.sender != owner) revert(); _; } // constructor called during creation of contract function FuBi() { owner = msg.sender; // person who deploy the contract will be the owner of the contract balances[owner] = totalSupply; // balance of owner will be equal to 20000 million } // implemented function balanceOf of erc20 to know the balnce of any account function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // transfer tokens from one address to another function transfer(address _to, uint _value) returns (bool success) { // Check send token value > 0; if(_value <= 0) throw; // Check if the sender has enough if (balances[msg.sender] < _value) throw; // Check for overflows if (balances[_to] + _value < balances[_to]) throw; // Subtract from the sender balances[msg.sender] -= _value; // Add the same to the recipient, if it's the contact itself then it signals a sell order of those tokens balances[_to] += _value; // Notify anyone listening that this transfer took place Transfer(msg.sender, _to, _value); return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns(bool success) { allowance[msg.sender][_spender] = _value; return true; } // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns(uint256 remaining) { return allowance[_owner][_spender]; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint _value) returns(bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balances[_from] < _value) throw; // Check if the sender has enough if (balances[_to] + _value < balances[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } // create new tokens, called only by owner, new token value supplied will be added to _to address with total supply function mint(address _to, uint256 _value) onlyOwner { if(!flag) { balances[_to] += _value; totalSupply += _value; } else revert(); } //owner can call this freeze function to freeze some accounts from doing certain functions function freeze(address target, bool freeze) onlyOwner { if(!flag) { frozenAccount[target] = freeze; FrozenFu(target,freeze); } else revert(); } // transfer the ownership to new address, called only by owner function transferOwnership(address to) public onlyOwner { owner = to; balances[owner]=balances[msg.sender]; balances[msg.sender]=0; } // flag function called by ony owner, stopping some function to work for function turn_flag_ON() onlyOwner { flag = true; } // flag function called by owner, releasing some function to work for function turn_flag_OFF() onlyOwner { flag = false; } //Drain Any Ether in contract to owner function drain() public onlyOwner { if (!owner.send(this.balance)) throw; } }
transfer the ownership to new address, called only by owner
function transferOwnership(address to) public onlyOwner { owner = to; balances[owner]=balances[msg.sender]; balances[msg.sender]=0; }
1,820,302
[ 1, 13866, 326, 23178, 358, 394, 1758, 16, 2566, 1338, 635, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 445, 7412, 5460, 12565, 12, 2867, 358, 13, 1071, 1338, 5541, 288, 203, 540, 3410, 273, 358, 31, 203, 540, 324, 26488, 63, 8443, 65, 33, 70, 26488, 63, 3576, 18, 15330, 15533, 203, 540, 324, 26488, 63, 3576, 18, 15330, 65, 33, 20, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x34bAF44866D73E7FC473e0FA2B22fd2713427F30/sources/lock.sol
* @notice Creates a new lock @param _amountToLock amount of LP tokens to lock @param _withdrawerAdd the user who can withdraw liquidity once the lock expires./ flatrate fees
function lockLPTokenWithoutTime(uint256 _amountToLock, address payable _withdrawerAdd) external payable nonReentrant { if(enableMaxPoolLimit==true) require(totalPoolParticipant>=tokenLocks[lpTokenAdd].length,'PARTICIPANTS EXCEED!'); TransferHelper.safeTransferFrom(lpTokenAdd, address(msg.sender), address(this), _amountToLock); bool _fee_in_eth= true; uint256 ethFee = vulcanFees.ethFee; require(msg.value == ethFee, 'FEE LESS PROVIDED'); uint256 devFee = ethFee; ownerAddr.transfer(devFee); } TokenLock memory token_lock; token_lock.lockDate = block.timestamp; token_lock.amount = _amountToLock; token_lock.startAmount = _amountToLock; token_lock.unlockDate = 0; token_lock.lockID = tokenLocks[lpTokenAdd].length; token_lock.owner = _withdrawerAdd; lockedUserTokens.add(lpTokenAdd); user.lockedUserTokens.add(lpTokenAdd); uint256[] storage user_locks = user.locksForToken[lpTokenAdd]; user_locks.push(token_lock.lockID); principleAmntToken+=_amountToLock; emit onDeposit(lpTokenAdd, msg.sender, token_lock.amount, token_lock.lockDate, token_lock.unlockDate);
4,683,160
[ 1, 2729, 279, 394, 2176, 225, 389, 8949, 774, 2531, 3844, 434, 511, 52, 2430, 358, 2176, 225, 389, 1918, 9446, 264, 986, 326, 729, 10354, 848, 598, 9446, 4501, 372, 24237, 3647, 326, 2176, 7368, 18, 19, 3569, 5141, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2176, 14461, 1345, 8073, 950, 12, 11890, 5034, 389, 8949, 774, 2531, 16, 1758, 8843, 429, 389, 1918, 9446, 264, 986, 13, 3903, 8843, 429, 1661, 426, 8230, 970, 288, 203, 203, 565, 309, 12, 7589, 2747, 2864, 3039, 631, 3767, 13, 203, 203, 565, 2583, 12, 4963, 2864, 22540, 34, 33, 2316, 19159, 63, 9953, 1345, 986, 8009, 2469, 11189, 15055, 2871, 2579, 6856, 55, 5675, 1441, 2056, 5124, 1769, 203, 377, 203, 565, 12279, 2276, 18, 4626, 5912, 1265, 12, 9953, 1345, 986, 16, 1758, 12, 3576, 18, 15330, 3631, 1758, 12, 2211, 3631, 389, 8949, 774, 2531, 1769, 203, 565, 1426, 389, 21386, 67, 267, 67, 546, 33, 638, 31, 203, 1377, 2254, 5034, 13750, 14667, 273, 331, 332, 4169, 2954, 281, 18, 546, 14667, 31, 203, 1377, 2583, 12, 3576, 18, 1132, 422, 13750, 14667, 16, 296, 8090, 41, 21216, 4629, 15472, 2056, 8284, 203, 1377, 2254, 5034, 4461, 14667, 273, 13750, 14667, 31, 203, 1377, 3410, 3178, 18, 13866, 12, 5206, 14667, 1769, 203, 565, 289, 7010, 27699, 203, 565, 3155, 2531, 3778, 1147, 67, 739, 31, 203, 565, 1147, 67, 739, 18, 739, 1626, 273, 1203, 18, 5508, 31, 203, 565, 1147, 67, 739, 18, 8949, 273, 389, 8949, 774, 2531, 31, 203, 565, 1147, 67, 739, 18, 1937, 6275, 273, 389, 8949, 774, 2531, 31, 203, 565, 1147, 67, 739, 18, 26226, 1626, 273, 374, 31, 203, 565, 1147, 67, 739, 18, 739, 734, 273, 1147, 19159, 63, 9953, 1345, 986, 8009, 2469, 31, 203, 2 ]
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BallerToken is Ownable, Destructible { using SafeMath for uint; /*** EVENTS ***/ // @dev Fired whenever a new Baller token is created for the first time. event BallerCreated(uint256 tokenId, string name, address owner); // @dev Fired whenever a Baller token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address newOwner, string name); // @dev Fired whenever a team is transfered from one owner to another event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ uint constant private DEFAULT_START_PRICE = 0.01 ether; uint constant private FIRST_PRICE_LIMIT = 0.5 ether; uint constant private SECOND_PRICE_LIMIT = 2 ether; uint constant private THIRD_PRICE_LIMIT = 5 ether; uint constant private FIRST_COMMISSION_LEVEL = 5; uint constant private SECOND_COMMISSION_LEVEL = 4; uint constant private THIRD_COMMISSION_LEVEL = 3; uint constant private FOURTH_COMMISSION_LEVEL = 2; uint constant private FIRST_LEVEL_INCREASE = 200; uint constant private SECOND_LEVEL_INCREASE = 135; uint constant private THIRD_LEVEL_INCREASE = 125; uint constant private FOURTH_LEVEL_INCREASE = 115; /*** STORAGE ***/ // @dev maps team id to address of who owns it mapping (uint => address) public teamIndexToOwner; // @dev maps team id to a price mapping (uint => uint) private teamIndexToPrice; // @dev maps address to how many tokens they own mapping (address => uint) private ownershipTokenCount; /*** DATATYPES ***/ //@dev struct for a baller team struct Team { string name; } //@dev array which holds each team Team[] private ballerTeams; /*** PUBLIC FUNCTIONS ***/ /** * @dev public function to create team, can only be called by owner of smart contract * @param _name the name of the team */ function createTeam(string _name, uint _price) public onlyOwner { _createTeam(_name, this, _price); } /** * @dev Returns all the relevant information about a specific team. * @param _tokenId The ID of the team. * @return teamName the name of the team. * @return currPrice what the team is currently worth. * @return owner address of whoever owns the team */ function getTeam(uint _tokenId) public view returns(string teamName, uint currPrice, address owner) { Team storage currTeam = ballerTeams[_tokenId]; teamName = currTeam.name; currPrice = teamIndexToPrice[_tokenId]; owner = ownerOf(_tokenId); } /** * @dev changes the name of a specific team. * @param _tokenId The id of the team which you want to change. * @param _newName The name you want to set the team to be. */ function changeTeamName(uint _tokenId, string _newName) public onlyOwner { require(_tokenId < ballerTeams.length); ballerTeams[_tokenId].name = _newName; } /** * @dev sends all ethereum in this contract to the address specified * @param _to address you want the eth to be sent to */ function payout(address _to) public onlyOwner { _withdrawAmount(_to, this.balance); } /** * @dev Function to send some amount of ethereum out of the contract to an address * @param _to address the eth will be sent to * @param _amount amount you want to withdraw */ function withdrawAmount(address _to, uint _amount) public onlyOwner { _withdrawAmount(_to, _amount); } /** * @dev Function to get price of a team * @param _teamId of team * @return price price of team */ function priceOfTeam(uint _teamId) public view returns (uint price, uint teamId) { price = teamIndexToPrice[_teamId]; teamId = _teamId; } /** * @dev Gets list of teams owned by a person. * @dev note: don't want to call this in the smart contract, expensive op. * @param _owner address of the owner * @return ownedTeams list of the teams owned by the owner */ function getTeamsOfOwner(address _owner) public view returns (uint[] ownedTeams) { uint tokenCount = balanceOf(_owner); ownedTeams = new uint[](tokenCount); uint totalTeams = totalSupply(); uint resultIndex = 0; if (tokenCount != 0) { for (uint pos = 0; pos < totalTeams; pos++) { address currOwner = ownerOf(pos); if (currOwner == _owner) { ownedTeams[resultIndex] = pos; resultIndex++; } } } } /* * @dev gets the address of owner of the team * @param _tokenId is id of the team * @return owner the owner of the team's address */ function ownerOf(uint _tokenId) public view returns (address owner) { owner = teamIndexToOwner[_tokenId]; require(owner != address(0)); } /* * @dev gets how many tokens an address owners * @param _owner is address of owner * @return numTeamsOwned how much teams he has */ function balanceOf(address _owner) public view returns (uint numTeamsOwned) { numTeamsOwned = ownershipTokenCount[_owner]; } /* * @dev gets total number of teams * @return totalNumTeams which is the number of teams */ function totalSupply() public view returns (uint totalNumTeams) { totalNumTeams = ballerTeams.length; } /** * @dev Allows user to buy a team from the old owner. * @dev Pays old owner minus commission, updates price. * @param _teamId id of the team they're trying to buy */ function purchase(uint _teamId) public payable { address oldOwner = ownerOf(_teamId); address newOwner = msg.sender; uint sellingPrice = teamIndexToPrice[_teamId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint payment = _calculatePaymentToOwner(sellingPrice); uint excessPayment = msg.value.sub(sellingPrice); uint newPrice = _calculateNewPrice(sellingPrice); teamIndexToPrice[_teamId] = newPrice; _transfer(oldOwner, newOwner, _teamId); // Pay old tokenOwner, unless it's the smart contract if (oldOwner != address(this)) { oldOwner.transfer(payment); } newOwner.transfer(excessPayment); string memory teamName = ballerTeams[_teamId].name; TokenSold(_teamId, sellingPrice, newPrice, oldOwner, newOwner, teamName); } /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /** * @dev Internal function to send some amount of ethereum out of the contract to an address * @param _to address the eth will be sent to * @param _amount amount you want to withdraw */ function _withdrawAmount(address _to, uint _amount) private { require(this.balance >= _amount); if (_to == address(0)) { owner.transfer(_amount); } else { _to.transfer(_amount); } } /** * @dev internal function to create team * @param _name the name of the team * @param _owner the owner of the team * @param _startingPrice the price of the team at the beginning */ function _createTeam(string _name, address _owner, uint _startingPrice) private { Team memory currTeam = Team(_name); uint newTeamId = ballerTeams.push(currTeam) - 1; // make sure we never overflow amount of tokens possible to be created // 4 billion tokens...shouldn't happen. require(newTeamId == uint256(uint32(newTeamId))); BallerCreated(newTeamId, _name, _owner); teamIndexToPrice[newTeamId] = _startingPrice; _transfer(address(0), _owner, newTeamId); } /** * @dev internal function to transfer ownership of team * @param _from original owner of token * @param _to the new owner * @param _teamId id of the team */ function _transfer(address _from, address _to, uint _teamId) private { ownershipTokenCount[_to]++; teamIndexToOwner[_teamId] = _to; // Creation of new team causes _from to be 0 if (_from != address(0)) { ownershipTokenCount[_from]--; } Transfer(_from, _to, _teamId); } /** * @dev internal function to calculate how much to give to owner of contract * @param _sellingPrice the current price of the team * @return payment amount the owner gets after commission. */ function _calculatePaymentToOwner(uint _sellingPrice) private pure returns (uint payment) { if (_sellingPrice < FIRST_PRICE_LIMIT) { payment = uint256(_sellingPrice.mul(100-FIRST_COMMISSION_LEVEL).div(100)); } else if (_sellingPrice < SECOND_PRICE_LIMIT) { payment = uint256(_sellingPrice.mul(100-SECOND_COMMISSION_LEVEL).div(100)); } else if (_sellingPrice < THIRD_PRICE_LIMIT) { payment = uint256(_sellingPrice.mul(100-THIRD_COMMISSION_LEVEL).div(100)); } else { payment = uint256(_sellingPrice.mul(100-FOURTH_COMMISSION_LEVEL).div(100)); } } /** * @dev internal function to calculate how much the new price is * @param _sellingPrice the current price of the team. * @return newPrice price the team will be worth after being bought. */ function _calculateNewPrice(uint _sellingPrice) private pure returns (uint newPrice) { if (_sellingPrice < FIRST_PRICE_LIMIT) { newPrice = uint256(_sellingPrice.mul(FIRST_LEVEL_INCREASE).div(100)); } else if (_sellingPrice < SECOND_PRICE_LIMIT) { newPrice = uint256(_sellingPrice.mul(SECOND_LEVEL_INCREASE).div(100)); } else if (_sellingPrice < THIRD_PRICE_LIMIT) { newPrice = uint256(_sellingPrice.mul(THIRD_LEVEL_INCREASE).div(100)); } else { newPrice = uint256(_sellingPrice.mul(FOURTH_LEVEL_INCREASE).div(100)); } } }
* @dev Function to get price of a team @param _teamId of team @return price price of team/
function priceOfTeam(uint _teamId) public view returns (uint price, uint teamId) { price = teamIndexToPrice[_teamId]; teamId = _teamId; }
1,518,029
[ 1, 2083, 358, 336, 6205, 434, 279, 5927, 225, 389, 10035, 548, 434, 5927, 327, 6205, 6205, 434, 5927, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6205, 951, 8689, 12, 11890, 389, 10035, 548, 13, 1071, 1476, 1135, 261, 11890, 6205, 16, 2254, 5927, 548, 13, 288, 203, 1377, 6205, 273, 5927, 1016, 774, 5147, 63, 67, 10035, 548, 15533, 203, 1377, 5927, 548, 273, 389, 10035, 548, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface CalleeInterface { /** * Allows users to send this contract arbitrary data. * @param _sender The msg.sender to Controller * @param _vaultOwner The vault owner * @param _vaultId The vault id * @param _data Arbitrary data given by the sender */ function callFunction( address payable _sender, address _vaultOwner, uint256 _vaultId, bytes memory _data ) external payable; } /** * @dev ZeroX Exchange contract interface. */ interface IZeroXExchange { // solhint-disable max-line-length /// @dev Canonical order structure. struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled. uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy. bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy. bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy. } struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s). uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract. } /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return fillResults Amounts filled and fees paid by maker and taker. function fillOrder( Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) external payable returns (FillResults memory fillResults); /// @dev Synchronously executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return totalFillResults Amounts filled and fees paid by makers and taker. /// NOTE: makerAssetFilledAmount and takerAssetFilledAmount may include amounts filled of different assets. function batchFillOrders( Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) external payable returns (FillResults memory totalFillResults); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface ERC20Interface { /** * @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); function decimals() external view returns (uint8); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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"); 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); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( ERC20Interface token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( ERC20Interface 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 * {ERC20Interface-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( ERC20Interface 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( ERC20Interface 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( ERC20Interface 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(ERC20Interface 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"); } } } /** * @author Opyn Team * @title Trade0x * @notice callee contract to trade on 0x. */ contract Trade0x is CalleeInterface { using SafeERC20 for ERC20Interface; IZeroXExchange public exchange; address public assetProxy; constructor(address _exchange, address _assetProxy) public { exchange = IZeroXExchange(_exchange); assetProxy = _assetProxy; // ERC20Interface(_weth).safeApprove(_assetProxy, uint256(-1)); } event Trade0xBatch(address indexed to, uint256 amount); event UnwrappedETH(address to, uint256 amount); function callFunction( address payable _sender, address, /* _vaultOwner */ uint256, /* _vaultId, */ bytes memory _data ) external override payable { // todo1: can only be called by controller. // todo2: can only be used to trade oTokens (IZeroXExchange.Order memory order, uint256 takerAssetFillAmount, bytes memory signature) = abi.decode( _data, (IZeroXExchange.Order, uint256, bytes) ); address makerAsset = decodeERC20Asset(order.makerAssetData); address takerAsset = decodeERC20Asset(order.takerAssetData); ERC20Interface(takerAsset).safeTransferFrom(_sender, address(this), takerAssetFillAmount); // approve the proxy if not done before uint256 allowance = ERC20Interface(takerAsset).allowance(address(this), assetProxy); if (allowance < takerAssetFillAmount) { ERC20Interface(takerAsset).approve(assetProxy, takerAssetFillAmount); } exchange.fillOrder{value: msg.value}(order, takerAssetFillAmount, signature); // transfer token to sender uint256 balance = ERC20Interface(makerAsset).balanceOf(address(this)); ERC20Interface(makerAsset).safeTransfer(_sender, balance); // transfer any excess fee back to user _sender.transfer(address(this).balance); } function decodeERC20Asset(bytes memory b) internal pure returns (address result) { require(b.length == 36, "LENGTH_65_REQUIRED"); uint256 index = 16; // 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 ZeroX Exchange contract interface./ solhint-disable max-line-length
interface IZeroXExchange { } struct Order { } struct FillResults { } }
2,304,022
[ 1, 7170, 60, 18903, 6835, 1560, 18, 19, 3704, 11317, 17, 8394, 943, 17, 1369, 17, 2469, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 7170, 60, 11688, 288, 203, 97, 203, 565, 1958, 4347, 288, 203, 565, 289, 203, 203, 565, 1958, 14192, 3447, 288, 203, 565, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xA225bd6B70Fcc0738350d4EE038A85a71532149F/sources/contracts/MafiaNuts.sol
check if user can mint in AL
function canClaimAL(address _address, bytes32[] calldata _merkleProof) public view returns (bool) { return !hasClaimed[_address] && MerkleProof.verify( _merkleProof, merkleRoot, keccak256(abi.encodePacked(_address)) ); }
1,870,573
[ 1, 1893, 309, 729, 848, 312, 474, 316, 7981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 848, 9762, 1013, 12, 2867, 389, 2867, 16, 1731, 1578, 8526, 745, 892, 389, 6592, 15609, 20439, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 7010, 565, 288, 203, 3639, 327, 401, 5332, 9762, 329, 63, 67, 2867, 65, 597, 31827, 20439, 18, 8705, 12, 203, 5411, 389, 6592, 15609, 20439, 16, 7010, 5411, 30235, 2375, 16, 203, 5411, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 2867, 3719, 203, 3639, 11272, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.15; contract IAugur { function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING } contract IOwnable { function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING } contract ITyped { function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING } library SafeMathUint256 { function MUL760(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 DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); return a - b; } function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a <= b) { return a; } else { return b; } } function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a >= b) { return a; } else { return b; } } function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING if (y > 3) { uint256 x = (y + 1) / 2; z = y; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING return 0; } function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING return a % b == 0; } // Float [fixed point] Operations function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, b), base); } function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, base), b); } } interface IERC1155 { event TRANSFERSINGLE49( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TRANSFERBATCH882( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event APPROVALFORALL731( //inject NONSTANDARD NAMING address indexed owner, address indexed operator, bool approved ); event URI998( //inject NONSTANDARD NAMING string value, uint256 indexed id ); function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING address from, address to, uint256 id, uint256 value, bytes calldata data ) external; function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFBATCH918( //inject NONSTANDARD NAMING address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } contract IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING // solhint-disable-next-line no-simple-event-func-name event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ICash is IERC20 { } contract ERC20 is IERC20 { using SafeMathUint256 for uint256; uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING uint256 public totalSupply; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_account]; } function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(msg.sender, _recipient, _amount); return true; } function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowances[_owner][_spender]; } function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, _amount); return true; } function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(_sender, _recipient, _amount); _APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount)); return true; } function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue)); return true; } function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue)); return true; } function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); balances[_sender] = balances[_sender].SUB692(_amount); balances[_recipient] = balances[_recipient].ADD571(_amount); emit TRANSFER723(_sender, _recipient, _amount); ONTOKENTRANSFER292(_sender, _recipient, _amount); } function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.ADD571(_amount); balances[_account] = balances[_account].ADD571(_amount); emit TRANSFER723(address(0), _account, _amount); } function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: burn from the zero address"); balances[_account] = balances[_account].SUB692(_amount); totalSupply = totalSupply.SUB692(_amount); emit TRANSFER723(_account, address(0), _amount); } function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); allowances[_owner][_spender] = _amount; emit APPROVAL665(_owner, _spender, _amount); } function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING _BURN356(_account, _amount); _APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount)); } // Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING } contract VariableSupplyToken is ERC20 { using SafeMathUint256 for uint256; function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _MINT880(_target, _amount); ONMINT315(_target, _amount); return true; } function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _BURN356(_target, _amount); ONBURN653(_target, _amount); return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING } } contract IAffiliateValidator { function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING } contract IDisputeWindow is ITyped, IERC20 { function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING } contract IReportingParticipant { function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING } contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 { function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING } contract IInitialReporter is IReportingParticipant, IOwnable { function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING } contract IReputationToken is IERC20 { function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING } contract IShareToken is ITyped, IERC1155 { function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING } contract IUniverse { function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING function FORK341() public returns (bool); //inject NONSTANDARD NAMING function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING } contract IV2ReputationToken is IReputationToken { function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING } library Reporting { uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING } contract IAugurTrading { function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING } contract IOrders { function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IMarket market; IAugur augur; IAugurTrading augurTrading; IShareToken shareToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken")); return Data({ market: _market, augur: _augur, augurTrading: _augurTrading, shareToken: _shareToken, cash: ICash(_augur.LOOKUP594("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING if (_orderData.id == bytes32(0)) { bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed)); } function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING GETORDERID157(_orderData, _orders); uint256[] memory _uints = new uint256[](5); _uints[0] = _orderData.amount; _uints[1] = _orderData.price; _uints[2] = _orderData.outcome; _uints[3] = _orderData.moneyEscrowed; _uints[4] = _orderData.sharesEscrowed; bytes32[] memory _bytes32s = new bytes32[](4); _bytes32s[0] = _orderData.betterOrderId; _bytes32s[1] = _orderData.worseOrderId; _bytes32s[2] = _tradeGroupId; _bytes32s[3] = _orderData.id; return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator); } } interface IUniswapV2Pair { event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP992( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM81(address to) external; //inject NONSTANDARD NAMING function SYNC86() external; //inject NONSTANDARD NAMING function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING } contract IRepSymbol { function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING } contract ReputationToken is VariableSupplyToken, IV2ReputationToken { using SafeMathUint256 for uint256; string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING IUniverse internal universe; IUniverse public parentUniverse; uint256 internal totalMigrated; IERC20 public legacyRepToken; IAugur public augur; address public warpSync; constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public { augur = _augur; universe = _universe; parentUniverse = _parentUniverse; warpSync = _augur.LOOKUP594("WarpSync"); legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken")); require(warpSync != address(0)); require(legacyRepToken != IERC20(0)); } function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe)); } function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(_attotokens > 0); IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators); IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35(); BURN234(msg.sender, _attotokens); _destination.MIGRATEIN692(msg.sender, _attotokens); return true; } function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING IUniverse _parentUniverse = parentUniverse; require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35()); require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510()); MINT146(_reporter, _attotokens); totalMigrated += _attotokens; // Update the fork tentative winner and finalize if we can if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) { _parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230()); } return true; } function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender); require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant)); // simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute uint256 _bonus = _amountMigrated.MUL760(2) / 5; MINT146(address(_reportingParticipant), _bonus); return true; } function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING require(warpSync == msg.sender); MINT146(_target, _amountToMint); universe.UPDATEFORKVALUES73(); return true; } function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); BURN234(msg.sender, _amountToBurn); return true; } function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(IUniverse(msg.sender) == universe); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING IUniverse _universe = _shadyReputationToken.GETUNIVERSE719(); require(universe.ISPARENTOF319(_universe)); require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken); } function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING return universe; } function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING return totalMigrated; } function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING return legacyRepToken; } function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _totalSupply = totalSupply; if (parentUniverse == IUniverse(0)) { return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0))); } else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) { return _totalSupply; } else { return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552(); } } function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]); } function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]); } function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]); } function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING require(parentUniverse == IUniverse(0)); uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender); require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance)); MINT146(msg.sender, _legacyBalance); return true; } }
inject NONSTANDARD NAMING
function ISFORKING853() public view returns (bool);
2,554,027
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4437, 7473, 47, 1360, 7140, 23, 1435, 1071, 1476, 1135, 261, 6430, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./Address.sol"; import "./Context.sol"; import "./Strings.sol"; import "./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 "./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 LICENSE pragma solidity ^0.8.0; interface IBattleground {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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; /** * @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 LICENSE pragma solidity ^0.8.0; interface IGOLD { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IRandomizer { function getChunkId() external view returns (uint256); function random(uint256 data) external returns (uint256); function randomChunk(uint256 chunkId, uint256 data) external returns (uint256); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { struct TokenTraits { bool isVillager; uint8 alphaIndex; } function getTokenTraits(uint256 tokenId) external view returns (TokenTraits memory); function generateTokenTraits(uint256 tokenId, uint256 seed) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IVAndV {} // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IVAndVMinter {} // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IVillage { function randomVikingOwner(uint256 seed) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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 "./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 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 LICENSE pragma solidity ^0.8.0; import "./Address.sol"; import "./Ownable.sol"; import "./Strings.sol"; import "./ERC721Enumerable.sol"; import "./IVAndV.sol"; import "./IVAndVMinter.sol"; import "./ITraits.sol"; import "./IVillage.sol"; import "./IBattleground.sol"; contract VAndV is IVAndV, ERC721Enumerable, Ownable { using Address for address; using Strings for uint256; // max number of tokens that can be minted - 75000 in production uint256 public immutable MAX_TOKENS; // number of tokens that can be claimed for free - 20% of MAX_TOKENS uint256 public immutable PAID_TOKENS; // number of tokens have been minted so far uint16 public minted = 0; // refernece to V&V minter IVAndVMinter private vandvMinter; // reference to village IVillage private village; // reference to battleground (coming soon) IBattleground private battleground; /** * create the contract with a name and symbol and references to other contracts * @param _maxTokens total tokens available */ constructor(uint256 _maxTokens) ERC721("Vikings & Villagers", "VANDV") { MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; } /** * mint a token to an address * @param to who to send the new token to */ function mint(address to) external returns (uint256) { require(_msgSender() == address(vandvMinter), "V&V: Only minter can call this function"); require(minted + 1 <= MAX_TOKENS, "V&V: All tokens minted"); minted++; _safeMint(to, minted); return minted; } /** * @param tokenId the token ID * @return the token's fully formed URI to get metadata */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked("https://vikingsandvillagers.com/metadata/", tokenId.toString())); } /** * @param from the address sending the token * @param to the address we're sending to * @param tokenId the token ID being transferred */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { // Hardcode approval for our contracts to transfer tokens to prevent users having // to manually approve their token for transfer, saving them gas if (_msgSender() != address(vandvMinter) && _msgSender() != address(village) && _msgSender() != address(battleground)) { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); } _transfer(from, to, tokenId); } /** * get how many tokens have been minted * @return number of tokens minted */ function getMinted() external view returns (uint16) { return minted; } /** * get the number of tokens available for minting ever * @return max tokens */ function getMaxTokens() external view returns (uint256) { return MAX_TOKENS; } /** * get the number of paid tokens * @return total paid tokens */ function getPaidTokens() external view returns (uint256) { return PAID_TOKENS; } /** * set the address of the V&V minter contract * @param _vandvMinter the address */ function setVAndVMinter(address _vandvMinter) external onlyOwner { vandvMinter = IVAndVMinter(_vandvMinter); } /** * set the address of the village contract * @param _village the address */ function setVillage(address _village) external onlyOwner { village = IVillage(_village); } /** * set the address of the battleground contract * doesn't exist yet, will be used in the future * @param _battleground the address */ function setBattleground(address _battleground) external onlyOwner { battleground = IBattleground(_battleground); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./Address.sol"; import "./Ownable.sol"; import "./Pausable.sol"; import "./ReentrancyGuard.sol"; import "./IERC721Receiver.sol"; import "./IVillage.sol"; import "./IRandomizer.sol"; import "./IGOLD.sol"; import "./ITraits.sol"; import "./VAndV.sol"; contract Village is IVillage, Ownable, IERC721Receiver, Pausable, ReentrancyGuard { using Address for address; // Events event GoldTaxed(address from, uint256 taxed); event GoldStolen(address from, uint256 total); // struct to store a stake's token, owner, and earning values struct Stake { uint16 tokenId; uint80 value; address owner; } // maximum alpha score for a viking uint8 public constant MAX_ALPHA = 8; // villagers earn 10000 $GOLD per day uint256 public constant DAILY_GOLD_RATE = 10000 ether; // villagers must have 2 days worth of $GOLD to unstake uint256 public constant MINIMUM_TO_EXIT = 2 days; // vikings take a 20% tax on all $GOLD earned uint256 public constant GOLD_CLAIM_TAX_PERCENTAGE = 20; // there will only ever be (roughly) 4 billion $GOLD earned through staking uint256 public constant MAXIMUM_GLOBAL_GOLD = 4000000000 ether; // total alpha scores staked uint256 public totalAlphaStaked = 0; // any rewards distributed when no vikings are staked uint256 public unaccountedRewards = 0; // amount of $GOLD due for each alpha point staked uint256 public rewardsPerAlpha = 0; // amount of $GOLD earned so far uint256 public totalGoldEarned = 0; // number of villagers staked uint256 public totalVillagersStaked = 0; // number of vikings staked uint256 public totalVikingsStaked = 0; // the last time $GOLD was claimed uint256 public lastClaimTimestamp = 0; // maps tokenId to stake mapping(uint256 => Stake) private village; // maps alpha to all viking raid parties with that alpha mapping(uint8 => Stake[]) private parties; // tracks location of each viking in raid parties mapping(uint256 => uint256) private partyIndices; // tracks token IDs owned by which addresses mapping(address => uint256[]) private ownerTokens; // tracks location of each token in owner tokens mapping(uint256 => uint256) private ownerTokensIndices; // reference to randomizer IRandomizer private randomizer; // reference to $GOLD IGOLD private gold; // reference to traits ITraits private traits; // reference to vandv VAndV private vandv; /** * create the contract */ constructor() { _pause(); } /** * add your villagers and vikings to the contract * @param tokenIds the IDs of the tokens to stake */ function stakeTokens(uint16[] calldata tokenIds) external nonReentrant whenNotPaused { require(tx.origin == _msgSender() && !_msgSender().isContract(), "VILLAGE: Only EOA"); for (uint i = 0; i < tokenIds.length; i++) { require(vandv.ownerOf(tokenIds[i]) == _msgSender(), "VILLAGE: Doesn't own that token"); vandv.transferFrom(_msgSender(), address(this), tokenIds[i]); ownerTokensIndices[tokenIds[i]] = ownerTokens[_msgSender()].length; ownerTokens[_msgSender()].push(tokenIds[i]); if (_isVillager(tokenIds[i])) { _addVillagerToVillage(_msgSender(), tokenIds[i]); } else { _addVikingToRaidParty(_msgSender(), tokenIds[i]); } } } /** * realize $GOLD earnings and optionally unstake tokens * @param tokenIds the IDs of the tokens to claim earnings from * @param shouldUnstake whether or not to unstake the tokens */ function claimEarnings(uint16[] calldata tokenIds, bool shouldUnstake) external nonReentrant whenNotPaused _updateEarnings { require(tx.origin == _msgSender() && !_msgSender().isContract(), "VILLAGE: Only EOA"); uint256 totalEarned = 0; for (uint i = 0; i < tokenIds.length; i++) { require(vandv.ownerOf(tokenIds[i]) == address(this), "VILLAGE: Token not owned by village contract"); if (_isVillager(tokenIds[i])) { totalEarned += _claimVillagerRewards(tokenIds[i], shouldUnstake); } else { totalEarned += _claimVikingRewards(tokenIds[i], shouldUnstake); } } if (totalEarned > 0) { gold.mint(_msgSender(), totalEarned); } } /** * get the token IDs owned by an address that are currently staked here * @param owner the owner's address * @return the token ids staked */ function getTokensForOwner(address owner) external view returns (uint256[] memory) { require(owner == _msgSender(), "VILLAGE: Only the owner can check their tokens"); return ownerTokens[owner]; } /** * calculate the total $GOLD earnings for a staked token * @param tokenId the token ID * @return the total earnings */ function getEarningsForToken(uint256 tokenId) external view returns (uint256) { uint256 owed = 0; if (_isVillager(tokenId)) { Stake memory stake = village[tokenId]; require(stake.owner == _msgSender(), "VILLAGE: Only the owner can check their earnings"); if (totalGoldEarned < MAXIMUM_GLOBAL_GOLD) { owed = (block.timestamp - stake.value) * DAILY_GOLD_RATE / 1 days; } else if (stake.value > lastClaimTimestamp) { owed = 0; // $GOLD production stopped already } else { owed = (lastClaimTimestamp - stake.value) * DAILY_GOLD_RATE / 1 days; // stop earning additional $GOLD if it's all been earned } } else { uint8 alpha = _alphaForViking(tokenId); Stake memory stake = parties[alpha][partyIndices[tokenId]]; require(stake.owner == _msgSender(), "VILLAGE: Only the owner can check their earnings"); owed = alpha * (rewardsPerAlpha - stake.value); } return owed; } /** * check if the owner can unstake a token * @param tokenId the token ID * @return whether the token can be unstaked */ function canUnstake(uint256 tokenId) external view returns (bool) { if (_isVillager(tokenId)) { Stake memory stake = village[tokenId]; require(stake.owner == _msgSender(), "VILLAGE: Only the owner can check their tokens"); return block.timestamp - stake.value >= MINIMUM_TO_EXIT; } else { uint8 alpha = _alphaForViking(tokenId); Stake memory stake = parties[alpha][partyIndices[tokenId]]; require(stake.owner == _msgSender(), "VILLAGE: Only the owner can check their tokens"); return true; } } /** * used by the minting contract to find a randomly staked viking to award * a stolen villager to * @param seed a random value to choose a viking from * @return the owner of the viking */ function randomVikingOwner(uint256 seed) external override view returns (address) { if (totalAlphaStaked == 0) { return address(0x0); } uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; // choose a value from 0 to total alpha staked uint256 cumulative; seed >>= 32; // loop through each bucket of vikings in parties until we find the correct bucket for (uint8 i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { cumulative += parties[i].length * i; if (bucket >= cumulative) { continue; } return parties[i][seed % parties[i].length].owner; } return address(0x0); } /** * @param from the address that sent the token * @return whether the token should be accepted */ function onERC721Received(address, address from, uint256, bytes calldata) external pure override returns (bytes4) { require(from == address(0x0), "VILLAGE: Cannot send tokens directly"); return IERC721Receiver.onERC721Received.selector; } /** * set the address of our randomizer contract * @param _randomizer the address */ function setRandomizer(address _randomizer) external onlyOwner { randomizer = IRandomizer(_randomizer); } /** * set the address of the gold contract * @param _gold the address */ function setGold(address _gold) external onlyOwner { gold = IGOLD(_gold); } /** * set the address of the traits contract * @param _traits the address */ function setTraits(address _traits) external onlyOwner { traits = ITraits(_traits); } /** * set the address of the V&V contract * @param _vandv the address */ function setVAndV(address _vandv) external onlyOwner { vandv = VAndV(_vandv); } /** * enables owner to pause/unpause staking/claiming * @param enabled if we should pause or unpause */ function setPaused(bool enabled) external onlyOwner { if (enabled) { _pause(); } else { _unpause(); } } /** * adds a villager to the village so they start producing $GOLD * @param owner the address of the staker * @param tokenId the token ID */ function _addVillagerToVillage(address owner, uint256 tokenId) internal _updateEarnings { village[tokenId] = Stake({ owner: owner, tokenId: uint16(tokenId), value: uint80(block.timestamp) }); totalVillagersStaked += 1; } /** * adds a viking to the relevant raid party with the same alpha score * @param owner the address of the staker * @param tokenId the token ID */ function _addVikingToRaidParty(address owner, uint256 tokenId) internal { uint8 alpha = _alphaForViking(tokenId); partyIndices[tokenId] = parties[alpha].length; parties[alpha].push(Stake({ owner: owner, tokenId: uint16(tokenId), value: uint80(rewardsPerAlpha) })); totalVikingsStaked += 1; totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5 } /** * figure out how much $GOLD the villager earned and do some accounting * if not unstaking, pay a 20% tax to the staked vikings * if unstaking, there is a 50% chance all $GOLD is stolen * @param tokenId the ID of the villager to claim earnings from * @param shouldUnstake whether or not to unstake the villager * @return owed the amount of $GOLD earned */ function _claimVillagerRewards(uint256 tokenId, bool shouldUnstake) internal returns (uint256 owed) { Stake memory stake = village[tokenId]; require(stake.owner == _msgSender(), "VILLAGE: Unable to claim because wrong owner"); if (shouldUnstake) { require(block.timestamp - stake.value >= MINIMUM_TO_EXIT, "VILLAGE: Can't unstake and claim yet"); } if (totalGoldEarned < MAXIMUM_GLOBAL_GOLD) { owed = (block.timestamp - stake.value) * DAILY_GOLD_RATE / 1 days; } else if (stake.value > lastClaimTimestamp) { owed = 0; // $GOLD production stopped already } else { owed = (lastClaimTimestamp - stake.value) * DAILY_GOLD_RATE / 1 days; // stop earning additional $GOLD if it's all been earned } if (shouldUnstake) { // 50% chance that all $GOLD is stolen by vikings if (randomizer.random(tokenId) & 1 == 1) { _addTaxedRewards(owed); emit GoldStolen(_msgSender(), owed); owed = 0; } delete village[tokenId]; uint256 lastTokenId = ownerTokens[_msgSender()][ownerTokens[_msgSender()].length - 1]; ownerTokens[_msgSender()][ownerTokensIndices[tokenId]] = lastTokenId; ownerTokensIndices[lastTokenId] = ownerTokensIndices[tokenId]; ownerTokens[_msgSender()].pop(); delete ownerTokensIndices[tokenId]; totalVillagersStaked -= 1; vandv.safeTransferFrom(address(this), _msgSender(), tokenId, ""); } else { uint256 tax = owed * GOLD_CLAIM_TAX_PERCENTAGE / 100; _addTaxedRewards(tax); emit GoldTaxed(_msgSender(), tax); owed -= tax; // reset the stake timestamp village[tokenId] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(block.timestamp) }); } } /** * claim earned $GOLD for staked vikings * @param tokenId the ID of the viking to claim earnings from * @param shouldUnstake whether or not to unstake the viking * @return owed the amount of $GOLD earned */ function _claimVikingRewards(uint256 tokenId, bool shouldUnstake) internal returns (uint256 owed) { uint8 alpha = _alphaForViking(tokenId); Stake memory stake = parties[alpha][partyIndices[tokenId]]; require(stake.owner == _msgSender(), "VILLAGE: Unable to claim because wrong owner"); owed = alpha * (rewardsPerAlpha - stake.value); if (shouldUnstake) { Stake memory lastStake = parties[alpha][parties[alpha].length - 1]; parties[alpha][partyIndices[tokenId]] = lastStake; partyIndices[lastStake.tokenId] = partyIndices[tokenId]; parties[alpha].pop(); delete partyIndices[tokenId]; uint256 lastTokenId = ownerTokens[_msgSender()][ownerTokens[_msgSender()].length - 1]; ownerTokens[_msgSender()][ownerTokensIndices[tokenId]] = lastTokenId; ownerTokensIndices[lastTokenId] = ownerTokensIndices[tokenId]; ownerTokens[_msgSender()].pop(); delete ownerTokensIndices[tokenId]; totalVikingsStaked -= 1; totalAlphaStaked -= alpha; vandv.safeTransferFrom(address(this), _msgSender(), tokenId, ""); } else { // reset the stake timestamp parties[alpha][partyIndices[tokenId]] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(rewardsPerAlpha) }); } } /** * do some accounting to add the $GOLD taxed from villagers when they * claim their earnings * @param amount the total $GOLD to add to the unclaimed rewards */ function _addTaxedRewards(uint256 amount) internal { // if there's no staked vikings keep track of the gold if (totalAlphaStaked == 0) { unaccountedRewards += amount; return; } rewardsPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked; unaccountedRewards = 0; } /** * checks if a token is a villager * @param tokenId the ID of the token to check * @return whether the token is a villager */ function _isVillager(uint256 tokenId) internal view returns (bool) { return traits.getTokenTraits(tokenId).isVillager; } /** * gets the alpha score for a viking * @param tokenId the token ID to check * @return the alpha score from 5-8 */ function _alphaForViking(uint256 tokenId) internal view returns (uint8) { return MAX_ALPHA - traits.getTokenTraits(tokenId).alphaIndex; } /** * make this function calculate the total $GOLD earned by villagers and * ensure we never go beyond the earnings cap */ modifier _updateEarnings() { if (totalGoldEarned < MAXIMUM_GLOBAL_GOLD) { totalGoldEarned += (block.timestamp - lastClaimTimestamp) * totalVillagersStaked * DAILY_GOLD_RATE / 1 days; lastClaimTimestamp = block.timestamp; } _; } }
there will only ever be (roughly) 4 billion $GOLD earned through staking
uint256 public constant MAXIMUM_GLOBAL_GOLD = 4000000000 ether;
78,758
[ 1, 18664, 903, 1338, 14103, 506, 261, 2642, 715, 13, 1059, 20714, 285, 271, 43, 11846, 425, 1303, 329, 3059, 384, 6159, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 5381, 4552, 18605, 67, 20402, 67, 43, 11846, 273, 1059, 2787, 11706, 225, 2437, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; // modules import "@erc725/smart-contracts/contracts/ERC725X.sol"; import "@erc725/smart-contracts/contracts/ERC725Y.sol"; // interfaces import "../LSP1UniversalReceiver/ILSP1UniversalReceiver.sol"; import "../LSP1UniversalReceiver/ILSP1UniversalReceiverDelegate.sol"; // library import "../Utils/ERC165CheckerCustom.sol"; // constants import "../LSP1UniversalReceiver/LSP1Constants.sol"; import "./LSP9Constants.sol"; /** * @title Core Implementation of LSP9Vault built on top of ERC725, LSP1UniversalReceiver * @author Fabian Vogelsteller, Yamen Merhi, Jean Cavallera * @dev Could be owned by a UniversalProfile and able to register received asset with UniversalReceiverDelegateVault */ contract LSP9VaultCore is ILSP1UniversalReceiver, ERC725XCore, ERC725YCore { /** * @notice Emitted when a native token is received * @param sender The address of the sender * @param value The amount of value sent */ event ValueReceived(address indexed sender, uint256 indexed value); // modifiers /** * @dev Modifier restricting the call to the owner of the contract and the UniversalReceiverDelegate */ modifier onlyAllowed() { if (msg.sender != owner()) { address universalReceiverAddress = address( bytes20(_getData(_LSP1_UNIVERSAL_RECEIVER_DELEGATE_KEY)) ); require( ERC165CheckerCustom.supportsERC165Interface( msg.sender, _INTERFACEID_LSP1_DELEGATE ) && msg.sender == universalReceiverAddress, "Only Owner or Universal Receiver Delegate allowed" ); } _; } // public functions /** * @dev Emits an event when a native token is received */ receive() external payable { emit ValueReceived(_msgSender(), msg.value); } // LSP1 /** * @notice Triggers the UniversalReceiver event when this function gets executed successfully. * @dev Forwards the call to the UniversalReceiverDelegate if set. * @param _typeId The type of call received. * @param _data The data received. */ function universalReceiver(bytes32 _typeId, bytes calldata _data) external virtual override returns (bytes memory returnValue) { bytes memory data = _getData(_LSP1_UNIVERSAL_RECEIVER_DELEGATE_KEY); if (data.length >= 20) { address universalReceiverDelegate = BytesLib.toAddress(data, 0); if ( ERC165CheckerCustom.supportsERC165Interface( universalReceiverDelegate, _INTERFACEID_LSP1_DELEGATE ) ) { returnValue = ILSP1UniversalReceiverDelegate( universalReceiverDelegate ).universalReceiverDelegate(_msgSender(), _typeId, _data); } } emit UniversalReceiver(_msgSender(), _typeId, returnValue, _data); } // internal functions /** * @dev Calls the universalReceiver function of the sender if supports LSP1 InterfaceId */ function _notifyVaultSender(address _sender) internal virtual { if ( ERC165CheckerCustom.supportsERC165Interface( _sender, _INTERFACEID_LSP1 ) ) { ILSP1UniversalReceiver(_sender).universalReceiver( _TYPEID_LSP9_VAULTSENDER, "" ); } } /** * @dev Calls the universalReceiver function of the recipient if supports LSP1 InterfaceId */ function _notifyVaultReceiver(address _receiver) internal virtual { if ( ERC165CheckerCustom.supportsERC165Interface( _receiver, _INTERFACEID_LSP1 ) ) { ILSP1UniversalReceiver(_receiver).universalReceiver( _TYPEID_LSP9_VAULTRECIPIENT, "" ); } } }
* @dev Modifier restricting the call to the owner of the contract and the UniversalReceiverDelegate/
modifier onlyAllowed() { if (msg.sender != owner()) { address universalReceiverAddress = address( bytes20(_getData(_LSP1_UNIVERSAL_RECEIVER_DELEGATE_KEY)) ); require( ERC165CheckerCustom.supportsERC165Interface( msg.sender, _INTERFACEID_LSP1_DELEGATE ) && msg.sender == universalReceiverAddress, "Only Owner or Universal Receiver Delegate allowed" ); } _; }
909,375
[ 1, 9829, 13108, 310, 326, 745, 358, 326, 3410, 434, 326, 6835, 471, 326, 27705, 12952, 9586, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5042, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 10756, 288, 203, 5411, 1758, 26182, 12952, 1887, 273, 1758, 12, 203, 7734, 1731, 3462, 24899, 588, 751, 24899, 3045, 52, 21, 67, 10377, 31879, 67, 27086, 45, 2204, 67, 1639, 19384, 1777, 67, 3297, 3719, 203, 5411, 11272, 203, 5411, 2583, 12, 203, 7734, 4232, 39, 28275, 8847, 3802, 18, 28064, 654, 39, 28275, 1358, 12, 203, 10792, 1234, 18, 15330, 16, 203, 10792, 389, 18865, 734, 67, 3045, 52, 21, 67, 1639, 19384, 1777, 203, 7734, 262, 597, 1234, 18, 15330, 422, 26182, 12952, 1887, 16, 203, 7734, 315, 3386, 16837, 578, 27705, 31020, 27687, 2935, 6, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xDda46bF18eeb3E06E2F12975A3A184e40581A72f/sources/_prb/math/src/ud60x18/Casting.sol
@notice Casts an UD60x18 number into SD59x18. @dev Requirements: - x must be less than or equal to `uMAX_SD59x18`.
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) { uint256 xUint = UD60x18.unwrap(x); if (xUint > uint256(uMAX_SD59x18)) { revert PRBMath_UD60x18_IntoSD59x18_Overflow(x); } result = SD59x18.wrap(int256(xUint)); }
3,094,346
[ 1, 9735, 87, 392, 587, 40, 4848, 92, 2643, 1300, 1368, 15951, 6162, 92, 2643, 18, 225, 29076, 30, 300, 619, 1297, 506, 5242, 2353, 578, 3959, 358, 1375, 89, 6694, 67, 9903, 6162, 92, 2643, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 1368, 9903, 6162, 92, 2643, 12, 12587, 4848, 92, 2643, 619, 13, 16618, 1135, 261, 9903, 6162, 92, 2643, 563, 13, 288, 203, 565, 2254, 5034, 619, 5487, 273, 587, 40, 4848, 92, 2643, 18, 318, 4113, 12, 92, 1769, 203, 565, 309, 261, 92, 5487, 405, 2254, 5034, 12, 89, 6694, 67, 9903, 6162, 92, 2643, 3719, 288, 203, 3639, 15226, 11770, 38, 10477, 67, 12587, 4848, 92, 2643, 67, 5952, 9903, 6162, 92, 2643, 67, 15526, 12, 92, 1769, 203, 565, 289, 203, 565, 563, 273, 15951, 6162, 92, 2643, 18, 4113, 12, 474, 5034, 12, 92, 5487, 10019, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x18e70C6485D3eF397f8C97D301e88B6977525123/sources/contracts/MathUtils.sol
add x^26 * (33! / 26!)
res += xi * 0x00000000000000000000005035ad900;
16,390,175
[ 1, 1289, 619, 66, 5558, 225, 261, 3707, 5, 342, 10659, 24949, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 400, 1011, 14087, 380, 374, 92, 12648, 12648, 9449, 3361, 4763, 361, 29, 713, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; import "./ConvexStrategy2Token.sol"; contract ConvexStrategyHBTCMainnet is ConvexStrategy2Token { address public hbtc_unused; // just a differentiator for the bytecode constructor() public {} function initializeStrategy( address _storage, address _vault ) public initializer { address underlying = address(0xb19059ebb43466C323583928285a49f558E572Fd); address rewardPool = address(0x618BD6cBA676a46958c63700C04318c84a7b7c0A); address crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); address wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); address hbtcCurveDeposit = address(0x4CA9b3063Ec5866A4B82E437059D2C43d1be596F); ConvexStrategy2Token.initializeBaseStrategy( _storage, underlying, _vault, rewardPool, //rewardPool 8, // Pool id wbtc, 1, //depositArrayPosition hbtcCurveDeposit, 0x00d10Fe4b76cA47E4e5206A93F10205b9C0c42a2, 1000 ); reward2WETH[crv] = [crv, weth]; reward2WETH[cvx] = [cvx, weth]; WETH2deposit = [weth, wbtc]; rewardTokens = [crv, cvx]; useUni[crv] = false; useUni[cvx] = false; useUni[wbtc] = false; } } pragma solidity 0.5.16; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../base/interface/uniswap/IUniswapV2Router02.sol"; import "../../base/interface/IStrategy.sol"; import "../../base/interface/IVault.sol"; import "../../base/upgradability/BaseUpgradeableStrategy.sol"; import "../../base/interface/uniswap/IUniswapV2Pair.sol"; import "./interface/IBooster.sol"; import "./interface/IBaseRewardPool.sol"; import "../../base/interface/curve/ICurveDeposit_2token.sol"; contract ConvexStrategy2Token is IStrategy, BaseUpgradeableStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant uniswapRouterV2 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant sushiswapRouterV2 = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); address public constant booster = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); // additional storage slots (on top of BaseUpgradeableStrategy ones) are defined here bytes32 internal constant _POOLID_SLOT = 0x3fd729bfa2e28b7806b03a6e014729f59477b530f995be4d51defc9dad94810b; bytes32 internal constant _DEPOSIT_TOKEN_SLOT = 0x219270253dbc530471c88a9e7c321b36afda219583431e7b6c386d2d46e70c86; bytes32 internal constant _DEPOSIT_RECEIPT_SLOT = 0x414478d5ad7f54ead8a3dd018bba4f8d686ba5ab5975cd376e0c98f98fb713c5; bytes32 internal constant _DEPOSIT_ARRAY_POSITION_SLOT = 0xb7c50ef998211fff3420379d0bf5b8dfb0cee909d1b7d9e517f311c104675b09; bytes32 internal constant _CURVE_DEPOSIT_SLOT = 0xb306bb7adebd5a22f5e4cdf1efa00bc5f62d4f5554ef9d62c1b16327cd3ab5f9; bytes32 internal constant _HODL_RATIO_SLOT = 0xb487e573671f10704ed229d25cf38dda6d287a35872859d096c0395110a0adb1; bytes32 internal constant _HODL_VAULT_SLOT = 0xc26d330f887c749cb38ae7c37873ff08ac4bba7aec9113c82d48a0cf6cc145f2; uint256 public constant hodlRatioBase = 10000; address[] public WETH2deposit; mapping (address => address[]) public reward2WETH; mapping (address => bool) public useUni; address[] public rewardTokens; constructor() public BaseUpgradeableStrategy() { assert(_POOLID_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.poolId")) - 1)); assert(_DEPOSIT_TOKEN_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.depositToken")) - 1)); assert(_DEPOSIT_RECEIPT_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.depositReceipt")) - 1)); assert(_DEPOSIT_ARRAY_POSITION_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.depositArrayPosition")) - 1)); assert(_CURVE_DEPOSIT_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.curveDeposit")) - 1)); assert(_HODL_RATIO_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.hodlRatio")) - 1)); assert(_HODL_VAULT_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.hodlVault")) - 1)); } function initializeBaseStrategy( address _storage, address _underlying, address _vault, address _rewardPool, uint256 _poolID, address _depositToken, uint256 _depositArrayPosition, address _curveDeposit, address _hodlVault, uint256 _hodlRatio ) public initializer { BaseUpgradeableStrategy.initialize( _storage, _underlying, _vault, _rewardPool, weth, 220, // profit sharing numerator. It is 22% because we remove 10% // before conversion. So, (1 - 0.1) * (1 - 0.22) ~= 0.702, or 30% reduction 1000, // profit sharing denominator true, // sell 0, // sell floor 12 hours // implementation change delay ); address _lpt; address _depositReceipt; (_lpt,_depositReceipt,,,,) = IBooster(booster).poolInfo(_poolID); require(_lpt == underlying(), "Pool Info does not match underlying"); require(_depositArrayPosition < 2, "Deposit array position out of bounds"); _setDepositArrayPosition(_depositArrayPosition); _setPoolId(_poolID); _setDepositToken(_depositToken); _setDepositReceipt(_depositReceipt); _setCurveDeposit(_curveDeposit); setHodlRatio(_hodlRatio); setHodlVault(_hodlVault); WETH2deposit = new address[](0); rewardTokens = new address[](0); } function setHodlRatio(uint256 _value) public onlyGovernance { setUint256(_HODL_RATIO_SLOT, _value); } function hodlRatio() public view returns (uint256) { return getUint256(_HODL_RATIO_SLOT); } function setHodlVault(address _address) public onlyGovernance { setAddress(_HODL_VAULT_SLOT, _address); } function hodlVault() public view returns (address) { return getAddress(_HODL_VAULT_SLOT); } function depositArbCheck() public view returns(bool) { return true; } function rewardPoolBalance() internal view returns (uint256 bal) { bal = IBaseRewardPool(rewardPool()).balanceOf(address(this)); } function exitRewardPool() internal { uint256 stakedBalance = rewardPoolBalance(); if (stakedBalance != 0) { IBaseRewardPool(rewardPool()).withdrawAll(true); } uint256 depositBalance = IERC20(depositReceipt()).balanceOf(address(this)); if (depositBalance != 0) { IBooster(booster).withdrawAll(poolId()); } } function partialWithdrawalRewardPool(uint256 amount) internal { IBaseRewardPool(rewardPool()).withdraw(amount, false); //don't claim rewards at this point uint256 depositBalance = IERC20(depositReceipt()).balanceOf(address(this)); if (depositBalance != 0) { IBooster(booster).withdrawAll(poolId()); } } function emergencyExitRewardPool() internal { uint256 stakedBalance = rewardPoolBalance(); if (stakedBalance != 0) { IBaseRewardPool(rewardPool()).withdrawAll(false); //don't claim rewards } uint256 depositBalance = IERC20(depositReceipt()).balanceOf(address(this)); if (depositBalance != 0) { IBooster(booster).withdrawAll(poolId()); } } function unsalvagableTokens(address token) public view returns (bool) { return (token == rewardToken() || token == underlying() || token == depositReceipt()); } function enterRewardPool() internal { uint256 entireBalance = IERC20(underlying()).balanceOf(address(this)); IERC20(underlying()).safeApprove(booster, 0); IERC20(underlying()).safeApprove(booster, entireBalance); IBooster(booster).depositAll(poolId(), true); //deposit and stake } /* * In case there are some issues discovered about the pool or underlying asset * Governance can exit the pool properly * The function is only used for emergency to exit the pool */ function emergencyExit() public onlyGovernance { emergencyExitRewardPool(); _setPausedInvesting(true); } /* * Resumes the ability to invest into the underlying reward pools */ function continueInvesting() public onlyGovernance { _setPausedInvesting(false); } function setDepositLiquidationPath(address [] memory _route) public onlyGovernance { require(_route[0] == weth, "Path should start with WETH"); require(_route[_route.length-1] == depositToken(), "Path should end with depositToken"); WETH2deposit = _route; } function setRewardLiquidationPath(address [] memory _route) public onlyGovernance { require(_route[_route.length-1] == weth, "Path should end with WETH"); bool isReward = false; for(uint256 i = 0; i < rewardTokens.length; i++){ if (_route[0] == rewardTokens[i]) { isReward = true; } } require(isReward, "Path should start with a rewardToken"); reward2WETH[_route[0]] = _route; } function addRewardToken(address _token, address[] memory _path2WETH) public onlyGovernance { require(_path2WETH[_path2WETH.length-1] == weth, "Path should end with WETH"); require(_path2WETH[0] == _token, "Path should start with rewardToken"); rewardTokens.push(_token); reward2WETH[_token] = _path2WETH; } // We assume that all the tradings can be done on Sushiswap function _liquidateReward() internal { if (!sell()) { // Profits can be disabled for possible simplified and rapoolId exit emit ProfitsNotCollected(sell(), false); return; } for(uint256 i = 0; i < rewardTokens.length; i++){ address token = rewardTokens[i]; uint256 rewardBalance = IERC20(token).balanceOf(address(this)); if (rewardBalance == 0 || reward2WETH[token].length < 2) { continue; } if (token == cvx) { uint256 toHodl = rewardBalance.mul(hodlRatio()).div(hodlRatioBase); if (toHodl > 0) { IERC20(cvx).safeTransfer(hodlVault(), toHodl); rewardBalance = rewardBalance.sub(toHodl); if (rewardBalance == 0) { continue; } } } address routerV2; if(useUni[token]) { routerV2 = uniswapRouterV2; } else { routerV2 = sushiswapRouterV2; } IERC20(token).safeApprove(routerV2, 0); IERC20(token).safeApprove(routerV2, rewardBalance); // we can accept 1 as the minimum because this will be called only by a trusted worker IUniswapV2Router02(routerV2).swapExactTokensForTokens( rewardBalance, 1, reward2WETH[token], address(this), block.timestamp ); } uint256 rewardBalance = IERC20(weth).balanceOf(address(this)); notifyProfitInRewardToken(rewardBalance); uint256 remainingRewardBalance = IERC20(rewardToken()).balanceOf(address(this)); if (remainingRewardBalance == 0) { return; } address routerV2; if(useUni[depositToken()]) { routerV2 = uniswapRouterV2; } else { routerV2 = sushiswapRouterV2; } // allow Uniswap to sell our reward IERC20(rewardToken()).safeApprove(routerV2, 0); IERC20(rewardToken()).safeApprove(routerV2, remainingRewardBalance); // we can accept 1 as minimum because this is called only by a trusted role uint256 amountOutMin = 1; IUniswapV2Router02(routerV2).swapExactTokensForTokens( remainingRewardBalance, amountOutMin, WETH2deposit, address(this), block.timestamp ); uint256 tokenBalance = IERC20(depositToken()).balanceOf(address(this)); if (tokenBalance > 0) { depositCurve(); } } function depositCurve() internal { uint256 tokenBalance = IERC20(depositToken()).balanceOf(address(this)); IERC20(depositToken()).safeApprove(curveDeposit(), 0); IERC20(depositToken()).safeApprove(curveDeposit(), tokenBalance); uint256[2] memory depositArray; depositArray[depositArrayPosition()] = tokenBalance; // we can accept 0 as minimum, this will be called only by trusted roles uint256 minimum = 0; ICurveDeposit_2token(curveDeposit()).add_liquidity(depositArray, minimum); } /* * Stakes everything the strategy holds into the reward pool */ function investAllUnderlying() internal onlyNotPausedInvesting { // this check is needed, because most of the SNX reward pools will revert if // you try to stake(0). if(IERC20(underlying()).balanceOf(address(this)) > 0) { enterRewardPool(); } } /* * Withdraws all the asset to the vault */ function withdrawAllToVault() public restricted { if (address(rewardPool()) != address(0)) { exitRewardPool(); } _liquidateReward(); IERC20(underlying()).safeTransfer(vault(), IERC20(underlying()).balanceOf(address(this))); } /* * Withdraws all the asset to the vault */ function withdrawToVault(uint256 amount) public restricted { // Typically there wouldn't be any amount here // however, it is possible because of the emergencyExit uint256 entireBalance = IERC20(underlying()).balanceOf(address(this)); if(amount > entireBalance){ // While we have the check above, we still using SafeMath below // for the peace of mind (in case something gets changed in between) uint256 needToWithdraw = amount.sub(entireBalance); uint256 toWithdraw = Math.min(rewardPoolBalance(), needToWithdraw); partialWithdrawalRewardPool(toWithdraw); } IERC20(underlying()).safeTransfer(vault(), amount); } /* * Note that we currently do not have a mechanism here to include the * amount of reward that is accrued. */ function investedUnderlyingBalance() external view returns (uint256) { return rewardPoolBalance() .add(IERC20(depositReceipt()).balanceOf(address(this))) .add(IERC20(underlying()).balanceOf(address(this))); } /* * Governance or Controller can claim coins that are somehow transferred into the contract * Note that they cannot come in take away coins that are used and defined in the strategy itself */ function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens(token), "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); } /* * Get the reward, sell it in exchange for underlying, invest what you got. * It's not much, but it's honest work. * * Note that although `onlyNotPausedInvesting` is not added here, * calling `investAllUnderlying()` affectively blocks the usage of `doHardWork` * when the investing is being paused by governance. */ function doHardWork() external onlyNotPausedInvesting restricted { IBaseRewardPool(rewardPool()).getReward(); _liquidateReward(); investAllUnderlying(); } /** * Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the * simplest possible way. */ function setSell(bool s) public onlyGovernance { _setSell(s); } /** * Sets the minimum amount of CRV needed to trigger a sale. */ function setSellFloor(uint256 floor) public onlyGovernance { _setSellFloor(floor); } // masterchef rewards pool ID function _setPoolId(uint256 _value) internal { setUint256(_POOLID_SLOT, _value); } function poolId() public view returns (uint256) { return getUint256(_POOLID_SLOT); } function _setDepositToken(address _address) internal { setAddress(_DEPOSIT_TOKEN_SLOT, _address); } function depositToken() public view returns (address) { return getAddress(_DEPOSIT_TOKEN_SLOT); } function _setDepositReceipt(address _address) internal { setAddress(_DEPOSIT_RECEIPT_SLOT, _address); } function depositReceipt() public view returns (address) { return getAddress(_DEPOSIT_RECEIPT_SLOT); } function _setDepositArrayPosition(uint256 _value) internal { setUint256(_DEPOSIT_ARRAY_POSITION_SLOT, _value); } function depositArrayPosition() public view returns (uint256) { return getUint256(_DEPOSIT_ARRAY_POSITION_SLOT); } function _setCurveDeposit(address _address) internal { setAddress(_CURVE_DEPOSIT_SLOT, _address); } function curveDeposit() public view returns (address) { return getAddress(_CURVE_DEPOSIT_SLOT); } function finalizeUpgrade() external onlyGovernance { _finalizeUpgrade(); setHodlVault(0x00d10Fe4b76cA47E4e5206A93F10205b9C0c42a2); setHodlRatio(1000); // 10% } } pragma solidity ^0.5.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); } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 { 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); 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; } pragma solidity 0.5.16; interface IStrategy { function unsalvagableTokens(address tokens) external view returns (bool); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function vault() external view returns (address); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch() // should only be called by controller function salvage(address recipient, address token, uint256 amount) external; function doHardWork() external; function depositArbCheck() external view returns(bool); } pragma solidity 0.5.16; interface IVault { function initializeVault( address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) external ; function balanceOf(address) external view returns (uint256); function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); // function store() external view returns (address); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function announceStrategyUpdate(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256); // hard work should be callable only by the controller (by the hard worker) or by governance function doHardWork() external; } pragma solidity 0.5.16; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./BaseUpgradeableStrategyStorage.sol"; import "../inheritance/ControllableInit.sol"; import "../interface/IController.sol"; import "../interface/IFeeRewardForwarderV6.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract BaseUpgradeableStrategy is Initializable, ControllableInit, BaseUpgradeableStrategyStorage { using SafeMath for uint256; using SafeERC20 for IERC20; event ProfitsNotCollected(bool sell, bool floor); event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); modifier restricted() { require(msg.sender == vault() || msg.sender == controller() || msg.sender == governance(), "The sender has to be the controller, governance, or vault"); _; } // This is only used in `investAllUnderlying()` // The user can still freely withdraw from the strategy modifier onlyNotPausedInvesting() { require(!pausedInvesting(), "Action blocked as the strategy is in emergency state"); _; } constructor() public BaseUpgradeableStrategyStorage() { } function initialize( address _storage, address _underlying, address _vault, address _rewardPool, address _rewardToken, uint256 _profitSharingNumerator, uint256 _profitSharingDenominator, bool _sell, uint256 _sellFloor, uint256 _implementationChangeDelay ) public initializer { ControllableInit.initialize( _storage ); _setUnderlying(_underlying); _setVault(_vault); _setRewardPool(_rewardPool); _setRewardToken(_rewardToken); _setProfitSharingNumerator(_profitSharingNumerator); _setProfitSharingDenominator(_profitSharingDenominator); _setSell(_sell); _setSellFloor(_sellFloor); _setNextImplementationDelay(_implementationChangeDelay); _setPausedInvesting(false); } /** * Schedules an upgrade for this vault's proxy. */ function scheduleUpgrade(address impl) public onlyGovernance { _setNextImplementation(impl); _setNextImplementationTimestamp(block.timestamp.add(nextImplementationDelay())); } function _finalizeUpgrade() internal { _setNextImplementation(address(0)); _setNextImplementationTimestamp(0); } function shouldUpgrade() external view returns (bool, address) { return ( nextImplementationTimestamp() != 0 && block.timestamp > nextImplementationTimestamp() && nextImplementation() != address(0), nextImplementation() ); } // reward notification function notifyProfitInRewardToken(uint256 _rewardBalance) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator()).div(profitSharingDenominator()); emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken()).safeApprove(controller(), 0); IERC20(rewardToken()).safeApprove(controller(), feeAmount); IController(controller()).notifyFee( rewardToken(), feeAmount ); } else { emit ProfitLogInReward(0, 0, block.timestamp); } } function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator()).div(profitSharingDenominator()); uint256 buybackAmount = _rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000); address forwarder = IController(controller()).feeRewardForwarder(); emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken()).safeApprove(forwarder, 0); IERC20(rewardToken()).safeApprove(forwarder, _rewardBalance); IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts( rewardToken(), feeAmount, pool, buybackAmount ); } else { emit ProfitAndBuybackLog(0, 0, block.timestamp); } } } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2020-05-05 */ // File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity 0.5.16; interface IBooster { function deposit(uint256 _pid, uint256 _amount, bool _stake) external; function depositAll(uint256 _pid, bool _stake) external; function withdraw(uint256 _pid, uint256 _amount) external; function withdrawAll(uint256 _pid) external; function poolInfo(uint256 _pid) external view returns (address lpToken, address, address, address, address, bool); function earmarkRewards(uint256 _pid) external; } pragma solidity 0.5.16; interface IBaseRewardPool { function balanceOf(address account) external view returns(uint256 amount); function pid() external view returns (uint256 _pid); function stakingToken() external view returns (address _stakingToken); function getReward() external; function stake(uint256 _amount) external; function stakeAll() external; function withdraw(uint256 amount, bool claim) external; function withdrawAll(bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function withdrawAllAndUnwrap(bool claim) external; } pragma solidity 0.5.16; interface ICurveDeposit_2token { function get_virtual_price() external view returns (uint); function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity( uint256 _amount, uint256[2] calldata amounts ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external payable; function calc_token_amount( uint256[2] calldata amounts, bool deposit ) external view returns(uint); } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; 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.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity 0.5.16; import "@openzeppelin/upgrades/contracts/Initializable.sol"; contract BaseUpgradeableStrategyStorage { bytes32 internal constant _UNDERLYING_SLOT = 0xa1709211eeccf8f4ad5b6700d52a1a9525b5f5ae1e9e5f9e5a0c2fc23c86e530; bytes32 internal constant _VAULT_SLOT = 0xefd7c7d9ef1040fc87e7ad11fe15f86e1d11e1df03c6d7c87f7e1f4041f08d41; bytes32 internal constant _REWARD_TOKEN_SLOT = 0xdae0aafd977983cb1e78d8f638900ff361dc3c48c43118ca1dd77d1af3f47bbf; bytes32 internal constant _REWARD_POOL_SLOT = 0x3d9bb16e77837e25cada0cf894835418b38e8e18fbec6cfd192eb344bebfa6b8; bytes32 internal constant _SELL_FLOOR_SLOT = 0xc403216a7704d160f6a3b5c3b149a1226a6080f0a5dd27b27d9ba9c022fa0afc; bytes32 internal constant _SELL_SLOT = 0x656de32df98753b07482576beb0d00a6b949ebf84c066c765f54f26725221bb6; bytes32 internal constant _PAUSED_INVESTING_SLOT = 0xa07a20a2d463a602c2b891eb35f244624d9068572811f63d0e094072fb54591a; bytes32 internal constant _PROFIT_SHARING_NUMERATOR_SLOT = 0xe3ee74fb7893020b457d8071ed1ef76ace2bf4903abd7b24d3ce312e9c72c029; bytes32 internal constant _PROFIT_SHARING_DENOMINATOR_SLOT = 0x0286fd414602b432a8c80a0125e9a25de9bba96da9d5068c832ff73f09208a3b; bytes32 internal constant _NEXT_IMPLEMENTATION_SLOT = 0x29f7fcd4fe2517c1963807a1ec27b0e45e67c60a874d5eeac7a0b1ab1bb84447; bytes32 internal constant _NEXT_IMPLEMENTATION_TIMESTAMP_SLOT = 0x414c5263b05428f1be1bfa98e25407cc78dd031d0d3cd2a2e3d63b488804f22e; bytes32 internal constant _NEXT_IMPLEMENTATION_DELAY_SLOT = 0x82b330ca72bcd6db11a26f10ce47ebcfe574a9c646bccbc6f1cd4478eae16b31; bytes32 internal constant _REWARD_CLAIMABLE_SLOT = 0xbc7c0d42a71b75c3129b337a259c346200f901408f273707402da4b51db3b8e7; bytes32 internal constant _MULTISIG_SLOT = 0x3e9de78b54c338efbc04e3a091b87dc7efb5d7024738302c548fc59fba1c34e6; constructor() public { assert(_UNDERLYING_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.underlying")) - 1)); assert(_VAULT_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.vault")) - 1)); assert(_REWARD_TOKEN_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.rewardToken")) - 1)); assert(_REWARD_POOL_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.rewardPool")) - 1)); assert(_SELL_FLOOR_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.sellFloor")) - 1)); assert(_SELL_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.sell")) - 1)); assert(_PAUSED_INVESTING_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.pausedInvesting")) - 1)); assert(_PROFIT_SHARING_NUMERATOR_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.profitSharingNumerator")) - 1)); assert(_PROFIT_SHARING_DENOMINATOR_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.profitSharingDenominator")) - 1)); assert(_NEXT_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.nextImplementation")) - 1)); assert(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.nextImplementationTimestamp")) - 1)); assert(_NEXT_IMPLEMENTATION_DELAY_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.nextImplementationDelay")) - 1)); assert(_REWARD_CLAIMABLE_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.rewardClaimable")) - 1)); assert(_MULTISIG_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.multiSig")) - 1)); } function _setUnderlying(address _address) internal { setAddress(_UNDERLYING_SLOT, _address); } function underlying() public view returns (address) { return getAddress(_UNDERLYING_SLOT); } function _setRewardPool(address _address) internal { setAddress(_REWARD_POOL_SLOT, _address); } function rewardPool() public view returns (address) { return getAddress(_REWARD_POOL_SLOT); } function _setRewardToken(address _address) internal { setAddress(_REWARD_TOKEN_SLOT, _address); } function rewardToken() public view returns (address) { return getAddress(_REWARD_TOKEN_SLOT); } function _setVault(address _address) internal { setAddress(_VAULT_SLOT, _address); } function vault() public view returns (address) { return getAddress(_VAULT_SLOT); } // a flag for disabling selling for simplified emergency exit function _setSell(bool _value) internal { setBoolean(_SELL_SLOT, _value); } function sell() public view returns (bool) { return getBoolean(_SELL_SLOT); } function _setPausedInvesting(bool _value) internal { setBoolean(_PAUSED_INVESTING_SLOT, _value); } function pausedInvesting() public view returns (bool) { return getBoolean(_PAUSED_INVESTING_SLOT); } function _setSellFloor(uint256 _value) internal { setUint256(_SELL_FLOOR_SLOT, _value); } function sellFloor() public view returns (uint256) { return getUint256(_SELL_FLOOR_SLOT); } function _setProfitSharingNumerator(uint256 _value) internal { setUint256(_PROFIT_SHARING_NUMERATOR_SLOT, _value); } function profitSharingNumerator() public view returns (uint256) { return getUint256(_PROFIT_SHARING_NUMERATOR_SLOT); } function _setProfitSharingDenominator(uint256 _value) internal { setUint256(_PROFIT_SHARING_DENOMINATOR_SLOT, _value); } function profitSharingDenominator() public view returns (uint256) { return getUint256(_PROFIT_SHARING_DENOMINATOR_SLOT); } function allowedRewardClaimable() public view returns (bool) { return getBoolean(_REWARD_CLAIMABLE_SLOT); } function _setRewardClaimable(bool _value) internal { setBoolean(_REWARD_CLAIMABLE_SLOT, _value); } function multiSig() public view returns(address) { return getAddress(_MULTISIG_SLOT); } function _setMultiSig(address _address) internal { setAddress(_MULTISIG_SLOT, _address); } // upgradeability function _setNextImplementation(address _address) internal { setAddress(_NEXT_IMPLEMENTATION_SLOT, _address); } function nextImplementation() public view returns (address) { return getAddress(_NEXT_IMPLEMENTATION_SLOT); } function _setNextImplementationTimestamp(uint256 _value) internal { setUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT, _value); } function nextImplementationTimestamp() public view returns (uint256) { return getUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT); } function _setNextImplementationDelay(uint256 _value) internal { setUint256(_NEXT_IMPLEMENTATION_DELAY_SLOT, _value); } function nextImplementationDelay() public view returns (uint256) { return getUint256(_NEXT_IMPLEMENTATION_DELAY_SLOT); } function setBoolean(bytes32 slot, bool _value) internal { setUint256(slot, _value ? 1 : 0); } function getBoolean(bytes32 slot) internal view returns (bool) { return (getUint256(slot) == 1); } function setAddress(bytes32 slot, address _address) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _address) } } function setUint256(bytes32 slot, uint256 _value) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _value) } } function getAddress(bytes32 slot) internal view returns (address str) { // solhint-disable-next-line no-inline-assembly assembly { str := sload(slot) } } function getUint256(bytes32 slot) internal view returns (uint256 str) { // solhint-disable-next-line no-inline-assembly assembly { str := sload(slot) } } } pragma solidity 0.5.16; import "./GovernableInit.sol"; // A clone of Governable supporting the Initializable interface and pattern contract ControllableInit is GovernableInit { constructor() public { } function initialize(address _storage) public initializer { GovernableInit.initialize(_storage); } modifier onlyController() { require(Storage(_storage()).isController(msg.sender), "Not a controller"); _; } modifier onlyControllerOrGovernance(){ require((Storage(_storage()).isController(msg.sender) || Storage(_storage()).isGovernance(msg.sender)), "The caller must be controller or governance"); _; } function controller() public view returns (address) { return Storage(_storage()).controller(); } } pragma solidity 0.5.16; interface IController { event SharePriceChangeLog( address indexed vault, address indexed strategy, uint256 oldSharePrice, uint256 newSharePrice, uint256 timestamp ); // [Grey list] // An EOA can safely interact with the system no matter what. // If you're using Metamask, you're using an EOA. // Only smart contracts may be affected by this grey list. // // This contract will not be able to ban any EOA from the system // even if an EOA is being added to the greyList, he/she will still be able // to interact with the whole system as if nothing happened. // Only smart contracts will be affected by being added to the greyList. // This grey list is only used in Vault.sol, see the code there for reference function greyList(address _target) external view returns(bool); function addVaultAndStrategy(address _vault, address _strategy) external; function doHardWork(address _vault) external; function salvage(address _token, uint256 amount) external; function salvageStrategy(address _strategy, address _token, uint256 amount) external; function notifyFee(address _underlying, uint256 fee) external; function profitSharingNumerator() external view returns (uint256); function profitSharingDenominator() external view returns (uint256); function feeRewardForwarder() external view returns(address); function setFeeRewardForwarder(address _value) external; function addHardWorker(address _worker) external; } pragma solidity 0.5.16; interface IFeeRewardForwarderV6 { function poolNotifyFixedTarget(address _token, uint256 _amount) external; function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function profitSharingPool() external view returns (address); function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external; } pragma solidity 0.5.16; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./Storage.sol"; // A clone of Governable supporting the Initializable interface and pattern contract GovernableInit is Initializable { bytes32 internal constant _STORAGE_SLOT = 0xa7ec62784904ff31cbcc32d09932a58e7f1e4476e1d041995b37c917990b16dc; modifier onlyGovernance() { require(Storage(_storage()).isGovernance(msg.sender), "Not governance"); _; } constructor() public { assert(_STORAGE_SLOT == bytes32(uint256(keccak256("eip1967.governableInit.storage")) - 1)); } function initialize(address _store) public initializer { _setStorage(_store); } function _setStorage(address newStorage) private { bytes32 slot = _STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newStorage) } } function setStorage(address _store) public onlyGovernance { require(_store != address(0), "new storage shouldn't be empty"); _setStorage(_store); } function _storage() internal view returns (address str) { bytes32 slot = _STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { str := sload(slot) } } function governance() public view returns (address) { return Storage(_storage()).governance(); } } pragma solidity 0.5.16; contract Storage { address public governance; address public controller; constructor() public { governance = msg.sender; } modifier onlyGovernance() { require(isGovernance(msg.sender), "Not governance"); _; } function setGovernance(address _governance) public onlyGovernance { require(_governance != address(0), "new governance shouldn't be empty"); governance = _governance; } function setController(address _controller) public onlyGovernance { require(_controller != address(0), "new controller shouldn't be empty"); controller = _controller; } function isGovernance(address account) public view returns (bool) { return account == governance; } function isController(address account) public view returns (bool) { return account == controller; } }
Stakes everything the strategy holds into the reward pool/ this check is needed, because most of the SNX reward pools will revert if you try to stake(0).
function investAllUnderlying() internal onlyNotPausedInvesting { if(IERC20(underlying()).balanceOf(address(this)) > 0) { enterRewardPool(); } }
141,731
[ 1, 510, 3223, 7756, 326, 6252, 14798, 1368, 326, 19890, 2845, 19, 333, 866, 353, 3577, 16, 2724, 4486, 434, 326, 14204, 60, 19890, 16000, 903, 15226, 309, 1846, 775, 358, 384, 911, 12, 20, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2198, 395, 1595, 14655, 6291, 1435, 2713, 1338, 1248, 28590, 3605, 10100, 288, 203, 565, 309, 12, 45, 654, 39, 3462, 12, 9341, 6291, 1435, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 405, 374, 13, 288, 203, 1377, 6103, 17631, 1060, 2864, 5621, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; // Inheritance import "./Owned.sol"; import "./MixinResolver.sol"; import "./MixinSystemSettings.sol"; import "./interfaces/ILiquidations.sol"; // Libraries import "./SafeDecimalMath.sol"; // Internal references import "./EternalStorage.sol"; import "./interfaces/IPeriFin.sol"; import "./interfaces/IExchangeRates.sol"; import "./interfaces/IIssuer.sol"; import "./interfaces/ISystemStatus.sol"; // /contracts/source/contracts/liquidations contract Liquidations is Owned, MixinSystemSettings, ILiquidations { using SafeMath for uint; using SafeDecimalMath for uint; struct LiquidationEntry { uint deadline; address caller; } /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_PYNTHETIX = "PeriFin"; bytes32 private constant CONTRACT_ETERNALSTORAGE_LIQUIDATIONS = "EternalStorageLiquidations"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; /* ========== CONSTANTS ========== */ // Storage keys bytes32 public constant LIQUIDATION_DEADLINE = "LiquidationDeadline"; bytes32 public constant LIQUIDATION_CALLER = "LiquidationCaller"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](5); newAddresses[0] = CONTRACT_SYSTEMSTATUS; newAddresses[1] = CONTRACT_PYNTHETIX; newAddresses[2] = CONTRACT_ETERNALSTORAGE_LIQUIDATIONS; newAddresses[3] = CONTRACT_ISSUER; newAddresses[4] = CONTRACT_EXRATES; addresses = combineArrays(existingAddresses, newAddresses); } function perifin() internal view returns (IPeriFin) { return IPeriFin(requireAndGetAddress(CONTRACT_PYNTHETIX)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } // refactor to perifin storage eternal storage contract once that's ready function eternalStorageLiquidations() internal view returns (EternalStorage) { return EternalStorage(requireAndGetAddress(CONTRACT_ETERNALSTORAGE_LIQUIDATIONS)); } function issuanceRatio() external view returns (uint) { return getIssuanceRatio(); } function liquidationDelay() external view returns (uint) { return getLiquidationDelay(); } function liquidationRatio() external view returns (uint) { return getLiquidationRatio(); } function liquidationPenalty() external view returns (uint) { return getLiquidationPenalty(); } function liquidationCollateralRatio() external view returns (uint) { return SafeDecimalMath.unit().divideDecimalRound(getLiquidationRatio()); } function getLiquidationDeadlineForAccount(address account) external view returns (uint) { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); return liquidation.deadline; } function isOpenForLiquidation(address account) external view returns (bool) { uint accountCollateralisationRatio = perifin().collateralisationRatio(account); // Liquidation closed if collateral ratio less than or equal target issuance Ratio // Account with no snx collateral will also not be open for liquidation (ratio is 0) if (accountCollateralisationRatio <= getIssuanceRatio()) { return false; } LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); // liquidation cap at issuanceRatio is checked above if (_deadlinePassed(liquidation.deadline)) { return true; } return false; } function isLiquidationDeadlinePassed(address account) external view returns (bool) { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); return _deadlinePassed(liquidation.deadline); } function _deadlinePassed(uint deadline) internal view returns (bool) { // check deadline is set > 0 // check now > deadline return deadline > 0 && now > deadline; } /** * r = target issuance ratio * D = debt balance * V = Collateral * P = liquidation penalty * Calculates amount of pynths = (D - V * r) / (1 - (1 + P) * r) */ function calculateAmountToFixCollateral(uint debtBalance, uint collateral) external view returns (uint) { uint ratio = getIssuanceRatio(); uint unit = SafeDecimalMath.unit(); uint dividend = debtBalance.sub(collateral.multiplyDecimal(ratio)); uint divisor = unit.sub(unit.add(getLiquidationPenalty()).multiplyDecimal(ratio)); return dividend.divideDecimal(divisor); } // get liquidationEntry for account // returns deadline = 0 when not set function _getLiquidationEntryForAccount(address account) internal view returns (LiquidationEntry memory _liquidation) { _liquidation.deadline = eternalStorageLiquidations().getUIntValue(_getKey(LIQUIDATION_DEADLINE, account)); // liquidation caller not used _liquidation.caller = address(0); } function _getKey(bytes32 _scope, address _account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_scope, _account)); } /* ========== MUTATIVE FUNCTIONS ========== */ // totalIssuedPynths checks pynths for staleness // check snx rate is not stale function flagAccountForLiquidation(address account) external rateNotInvalid("PERI") { systemStatus().requireSystemActive(); require(getLiquidationRatio() > 0, "Liquidation ratio not set"); require(getLiquidationDelay() > 0, "Liquidation delay not set"); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline == 0, "Account already flagged for liquidation"); uint accountsCollateralisationRatio = perifin().collateralisationRatio(account); // if accounts issuance ratio is greater than or equal to liquidation ratio set liquidation entry require( accountsCollateralisationRatio >= getLiquidationRatio(), "Account issuance ratio is less than liquidation ratio" ); uint deadline = now.add(getLiquidationDelay()); _storeLiquidationEntry(account, deadline, msg.sender); emit AccountFlaggedForLiquidation(account, deadline); } // Internal function to remove account from liquidations // Does not check collateral ratio is fixed function removeAccountInLiquidation(address account) external onlyIssuer { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); if (liquidation.deadline > 0) { _removeLiquidationEntry(account); } } // Public function to allow an account to remove from liquidations // Checks collateral ratio is fixed - below target issuance ratio // Check PERI rate is not stale function checkAndRemoveAccountInLiquidation(address account) external rateNotInvalid("PERI") { systemStatus().requireSystemActive(); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline > 0, "Account has no liquidation set"); uint accountsCollateralisationRatio = perifin().collateralisationRatio(account); // Remove from liquidations if accountsCollateralisationRatio is fixed (less than equal target issuance ratio) if (accountsCollateralisationRatio <= getIssuanceRatio()) { _removeLiquidationEntry(account); } } function _storeLiquidationEntry( address _account, uint _deadline, address _caller ) internal { // record liquidation deadline eternalStorageLiquidations().setUIntValue(_getKey(LIQUIDATION_DEADLINE, _account), _deadline); eternalStorageLiquidations().setAddressValue(_getKey(LIQUIDATION_CALLER, _account), _caller); } function _removeLiquidationEntry(address _account) internal { // delete liquidation deadline eternalStorageLiquidations().deleteUIntValue(_getKey(LIQUIDATION_DEADLINE, _account)); // delete liquidation caller eternalStorageLiquidations().deleteAddressValue(_getKey(LIQUIDATION_CALLER, _account)); emit AccountRemovedFromLiquidation(_account, now); } /* ========== MODIFIERS ========== */ modifier onlyIssuer() { require(msg.sender == address(issuer()), "Liquidations: Only the Issuer contract can perform this action"); _; } modifier rateNotInvalid(bytes32 currencyKey) { require(!exchangeRates().rateIsInvalid(currencyKey), "Rate invalid or not a pynth"); _; } /* ========== EVENTS ========== */ event AccountFlaggedForLiquidation(address indexed account, uint deadline); event AccountRemovedFromLiquidation(address indexed account, uint time); }
/contracts/source/contracts/liquidations
contract Liquidations is Owned, MixinSystemSettings, ILiquidations { using SafeMath for uint; using SafeDecimalMath for uint; import "./Owned.sol"; import "./SafeDecimalMath.sol"; import "./EternalStorage.sol"; struct LiquidationEntry { uint deadline; address caller; } bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_PYNTHETIX = "PeriFin"; bytes32 private constant CONTRACT_ETERNALSTORAGE_LIQUIDATIONS = "EternalStorageLiquidations"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 public constant LIQUIDATION_CALLER = "LiquidationCaller"; bytes32 public constant LIQUIDATION_DEADLINE = "LiquidationDeadline"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](5); newAddresses[0] = CONTRACT_SYSTEMSTATUS; newAddresses[1] = CONTRACT_PYNTHETIX; newAddresses[2] = CONTRACT_ETERNALSTORAGE_LIQUIDATIONS; newAddresses[3] = CONTRACT_ISSUER; newAddresses[4] = CONTRACT_EXRATES; addresses = combineArrays(existingAddresses, newAddresses); } function perifin() internal view returns (IPeriFin) { return IPeriFin(requireAndGetAddress(CONTRACT_PYNTHETIX)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function eternalStorageLiquidations() internal view returns (EternalStorage) { return EternalStorage(requireAndGetAddress(CONTRACT_ETERNALSTORAGE_LIQUIDATIONS)); } function issuanceRatio() external view returns (uint) { return getIssuanceRatio(); } function liquidationDelay() external view returns (uint) { return getLiquidationDelay(); } function liquidationRatio() external view returns (uint) { return getLiquidationRatio(); } function liquidationPenalty() external view returns (uint) { return getLiquidationPenalty(); } function liquidationCollateralRatio() external view returns (uint) { return SafeDecimalMath.unit().divideDecimalRound(getLiquidationRatio()); } function getLiquidationDeadlineForAccount(address account) external view returns (uint) { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); return liquidation.deadline; } function isOpenForLiquidation(address account) external view returns (bool) { uint accountCollateralisationRatio = perifin().collateralisationRatio(account); if (accountCollateralisationRatio <= getIssuanceRatio()) { return false; } LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); if (_deadlinePassed(liquidation.deadline)) { return true; } return false; } function isOpenForLiquidation(address account) external view returns (bool) { uint accountCollateralisationRatio = perifin().collateralisationRatio(account); if (accountCollateralisationRatio <= getIssuanceRatio()) { return false; } LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); if (_deadlinePassed(liquidation.deadline)) { return true; } return false; } function isOpenForLiquidation(address account) external view returns (bool) { uint accountCollateralisationRatio = perifin().collateralisationRatio(account); if (accountCollateralisationRatio <= getIssuanceRatio()) { return false; } LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); if (_deadlinePassed(liquidation.deadline)) { return true; } return false; } function isLiquidationDeadlinePassed(address account) external view returns (bool) { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); return _deadlinePassed(liquidation.deadline); } function _deadlinePassed(uint deadline) internal view returns (bool) { return deadline > 0 && now > deadline; } function calculateAmountToFixCollateral(uint debtBalance, uint collateral) external view returns (uint) { uint ratio = getIssuanceRatio(); uint unit = SafeDecimalMath.unit(); uint dividend = debtBalance.sub(collateral.multiplyDecimal(ratio)); uint divisor = unit.sub(unit.add(getLiquidationPenalty()).multiplyDecimal(ratio)); return dividend.divideDecimal(divisor); } function _getLiquidationEntryForAccount(address account) internal view returns (LiquidationEntry memory _liquidation) { _liquidation.deadline = eternalStorageLiquidations().getUIntValue(_getKey(LIQUIDATION_DEADLINE, account)); _liquidation.caller = address(0); } function _getKey(bytes32 _scope, address _account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_scope, _account)); } function flagAccountForLiquidation(address account) external rateNotInvalid("PERI") { systemStatus().requireSystemActive(); require(getLiquidationRatio() > 0, "Liquidation ratio not set"); require(getLiquidationDelay() > 0, "Liquidation delay not set"); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline == 0, "Account already flagged for liquidation"); uint accountsCollateralisationRatio = perifin().collateralisationRatio(account); require( accountsCollateralisationRatio >= getLiquidationRatio(), "Account issuance ratio is less than liquidation ratio" ); uint deadline = now.add(getLiquidationDelay()); _storeLiquidationEntry(account, deadline, msg.sender); emit AccountFlaggedForLiquidation(account, deadline); } function removeAccountInLiquidation(address account) external onlyIssuer { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); if (liquidation.deadline > 0) { _removeLiquidationEntry(account); } } function removeAccountInLiquidation(address account) external onlyIssuer { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); if (liquidation.deadline > 0) { _removeLiquidationEntry(account); } } function checkAndRemoveAccountInLiquidation(address account) external rateNotInvalid("PERI") { systemStatus().requireSystemActive(); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline > 0, "Account has no liquidation set"); uint accountsCollateralisationRatio = perifin().collateralisationRatio(account); if (accountsCollateralisationRatio <= getIssuanceRatio()) { _removeLiquidationEntry(account); } } function checkAndRemoveAccountInLiquidation(address account) external rateNotInvalid("PERI") { systemStatus().requireSystemActive(); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline > 0, "Account has no liquidation set"); uint accountsCollateralisationRatio = perifin().collateralisationRatio(account); if (accountsCollateralisationRatio <= getIssuanceRatio()) { _removeLiquidationEntry(account); } } function _storeLiquidationEntry( address _account, uint _deadline, address _caller ) internal { eternalStorageLiquidations().setUIntValue(_getKey(LIQUIDATION_DEADLINE, _account), _deadline); eternalStorageLiquidations().setAddressValue(_getKey(LIQUIDATION_CALLER, _account), _caller); } function _removeLiquidationEntry(address _account) internal { eternalStorageLiquidations().deleteUIntValue(_getKey(LIQUIDATION_DEADLINE, _account)); eternalStorageLiquidations().deleteAddressValue(_getKey(LIQUIDATION_CALLER, _account)); emit AccountRemovedFromLiquidation(_account, now); } modifier onlyIssuer() { require(msg.sender == address(issuer()), "Liquidations: Only the Issuer contract can perform this action"); _; } modifier rateNotInvalid(bytes32 currencyKey) { require(!exchangeRates().rateIsInvalid(currencyKey), "Rate invalid or not a pynth"); _; } event AccountFlaggedForLiquidation(address indexed account, uint deadline); event AccountRemovedFromLiquidation(address indexed account, uint time); }
12,708,900
[ 1, 19, 16351, 87, 19, 3168, 19, 16351, 87, 19, 549, 26595, 1012, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 18988, 350, 1012, 353, 14223, 11748, 16, 490, 10131, 3163, 2628, 16, 467, 48, 18988, 350, 1012, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 14060, 5749, 10477, 364, 2254, 31, 203, 203, 5666, 25165, 5460, 329, 18, 18281, 14432, 203, 5666, 25165, 9890, 5749, 10477, 18, 18281, 14432, 203, 5666, 25165, 41, 1174, 3245, 18, 18281, 14432, 203, 565, 1958, 511, 18988, 350, 367, 1622, 288, 203, 3639, 2254, 14096, 31, 203, 3639, 1758, 4894, 31, 203, 565, 289, 203, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 14318, 8608, 273, 315, 3163, 1482, 14432, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 16235, 1784, 44, 1584, 12507, 273, 315, 2173, 77, 6187, 14432, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 1584, 654, 50, 1013, 19009, 67, 2053, 53, 3060, 15297, 273, 315, 41, 1174, 3245, 48, 18988, 350, 1012, 14432, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 25689, 57, 654, 273, 315, 16667, 14432, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 2294, 24062, 55, 273, 315, 11688, 20836, 14432, 203, 203, 565, 1731, 1578, 1071, 5381, 8961, 53, 3060, 2689, 67, 13730, 654, 273, 315, 48, 18988, 350, 367, 11095, 14432, 203, 203, 203, 203, 203, 565, 1731, 1578, 1071, 5381, 8961, 53, 3060, 2689, 67, 1639, 1880, 5997, 273, 315, 48, 18988, 350, 367, 15839, 14432, 203, 565, 3885, 12, 2867, 389, 8443, 16, 1758, 389, 14122, 13, 1071, 14223, 11748, 24899, 2 ]
./full_match/5/0x975Ce475Dfd8Bf708D6154397EE71aaecB706695/sources/BankNegara.sol
the person deploy the smart contract. so u basically have more than one person at time, aka this thing is not being connected to any sort of service, just local solidity contract nothing fancy
address public currentuser;
1,855,665
[ 1, 5787, 6175, 7286, 326, 13706, 6835, 18, 1427, 582, 23772, 1240, 1898, 2353, 1245, 6175, 622, 813, 16, 28105, 333, 7757, 353, 486, 3832, 5840, 358, 1281, 1524, 434, 1156, 16, 2537, 1191, 18035, 560, 6835, 5083, 31701, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 783, 1355, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; library strUtils { /* Converts given number to base58, limited by _maxLength symbols */ function toBase58(uint256 _value, uint8 _maxLength) internal pure returns (string) { string memory letters = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; bytes memory alphabet = bytes(letters); uint8 base = 58; uint8 len = 0; uint256 remainder = 0; bool needBreak = false; bytes memory bytesReversed = bytes(new string(_maxLength)); for (uint8 i = 0; i < _maxLength; i++) { if(_value < base){ needBreak = true; } remainder = _value % base; _value = uint256(_value / base); bytesReversed[i] = alphabet[remainder]; len++; if(needBreak){ break; } } // Reverse bytes memory result = bytes(new string(len)); for (i = 0; i < len; i++) { result[i] = bytesReversed[len - i - 1]; } return string(result); } /* Concatenates two strings */ function concat(string _s1, string _s2) internal pure returns (string) { bytes memory bs1 = bytes(_s1); bytes memory bs2 = bytes(_s2); string memory s3 = new string(bs1.length + bs2.length); bytes memory bs3 = bytes(s3); uint256 j = 0; for (uint256 i = 0; i < bs1.length; i++) { bs3[j++] = bs1[i]; } for (i = 0; i < bs2.length; i++) { bs3[j++] = bs2[i]; } return string(bs3); } } contract EthTxt { event NewText(string text, string code, address submitter, uint timestamp); struct StoredText { string text; address submitter; uint timestamp; } uint storedTextCount = 0; // change this to 0 for testnet / ropsten uint blockoffset = 4000000; mapping (string => StoredText) texts; // this is the constructor function EthTxt() public { // do nothing here } function archiveText(string _text) public { // make sure _text is not an empty string require(bytes(_text).length != 0); var code = _generateShortLink(); // make sure code doesnt exist in map require(bytes(getText(code)).length == 0); // add text to map texts[code] = StoredText(_text, msg.sender, now); NewText(_text, code, msg.sender, now); storedTextCount = storedTextCount + 1; } function getText(string _code) public view returns (string) { return texts[_code].text; } function getTextCount() public view returns (uint) { return storedTextCount; } // Generates a shortlink code function _generateShortLink() private view returns (string) { var s1 = strUtils.toBase58(uint256(msg.sender), 2); var s2 = strUtils.toBase58(block.number - blockoffset, 11); var s = strUtils.concat(s1, s2); return s; } }
change this to 0 for testnet / ropsten
uint blockoffset = 4000000;
14,116,522
[ 1, 3427, 333, 358, 374, 364, 1842, 2758, 342, 721, 84, 334, 275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 1203, 3348, 273, 1059, 9449, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Staking3Months is OwnableUpgradeable { mapping(address => uint256) private _stakes; string public name; uint256 public stakingStarts; uint256 public stakingEnds; uint256 public stakingCap;// = 1000000 ether; uint256 public depositTime;//= 90 days; uint256 public rewardPerc;// = 175; //17.5 % uint256 public stakedTotal; uint256 public tokensForBurning; address public rewardAddress; bool private depositEnabled; IERC20 token; mapping(address => uint256) public deposited; event Staked( address indexed token, address indexed staker_, uint256 requestedAmount_, uint256 stakedAmount_ ); event PaidOut( address indexed token, address indexed staker_, uint256 amount_, uint256 reward_ ); event EmergencyWithdrawDone( address indexed sender, address indexed token, uint256 amount_ ); event EmergencyWithdrawAdminDone( address indexed sender, address indexed token, uint256 amount_ ); event DepositEnabledSet(bool value); event StakingCapSet(uint256 value); event DepositTimeSet(uint256 value); event RewardPercSet(uint256 value); event RewardAddressChanged( address indexed sender, address indexed rewardAddress ); modifier _after(uint256 eventTime) { require( block.timestamp >= eventTime, "Error: bad timing for the request" ); _; } modifier _before(uint256 eventTime) { require( block.timestamp < eventTime, "Error: bad timing for the request" ); _; } constructor(){ } function initialize(string memory name_, address _token, uint256 _stakingStarts, uint256 _stakingEnds, address _rewardAddress, uint256 _rewardPerc, uint256 _depositTime, uint256 _stakingCap) public initializer{ require(_rewardAddress != address(0), "_rewardAddress should not be 0"); __Ownable_init(); depositEnabled = true; name = name_; token = IERC20(_token); stakingStarts = _stakingStarts; stakingEnds = _stakingEnds; rewardAddress = _rewardAddress; rewardPerc = _rewardPerc; depositTime = _depositTime; stakingCap = _stakingCap; } function stakeOf(address account) external view returns (uint256) { return _stakes[account]; } function timeStaked(address account) external view returns (uint256) { return deposited[account]; } function canWithdraw(address _addy) external view returns (bool) { if (block.timestamp >= deposited[_addy]+(depositTime)) { return true; } else { return false; } } /** * Requirements: * - `amount` Amount to be staked */ function stake(uint256 amount) external { require(depositEnabled,"Deposits not enabled"); _stake(msg.sender, amount); } function getBurnStat() public view returns(uint256){ return tokensForBurning; } function withdraw() external { require( block.timestamp >= deposited[msg.sender]+(depositTime), "Error: Staking period not passed yet" ); uint256 amount = _stakes[msg.sender]; tokensForBurning += amount; _withdrawAfterClose(msg.sender, amount); } function _withdrawAfterClose(address from, uint256 amount) private { uint256 reward = amount*(rewardPerc)/(1000); _stakes[from] = _stakes[from]-(amount); stakedTotal = stakedTotal-(amount); emit PaidOut(address(token), from, amount, reward); token.transferFrom(rewardAddress, from, reward); //transfer Reward token.transfer(from, amount); //transfer initial stake } function _stake(address staker, uint256 amount) private _after(stakingStarts) _before(stakingEnds) { // check the remaining amount to be staked uint256 remaining = amount; if (remaining > (stakingCap-(stakedTotal))) { remaining = stakingCap-(stakedTotal); } // These requires are not necessary, because it will never happen, but won't hurt to double check // this is because stakedTotal is only modified in this method during the staking period require(remaining > 0, "Error: Staking cap is filled"); require( (remaining+(stakedTotal)) <= stakingCap, "Error: this will increase staking amount pass the cap" ); stakedTotal = stakedTotal+(remaining); _stakes[staker] = _stakes[staker]+(remaining); deposited[msg.sender] = block.timestamp; emit Staked(address(token), staker, amount, remaining); token.transferFrom(staker, address(this), remaining); } function setRewardPerc(uint256 _rewardPerc) external onlyOwner{ rewardPerc = _rewardPerc; emit RewardPercSet(_rewardPerc); } function setDepositTime(uint256 _depositTime) external onlyOwner{ depositTime = _depositTime; emit DepositTimeSet(_depositTime); } function setStakingCap(uint256 _stakingCap) external onlyOwner{ stakingCap = _stakingCap; emit StakingCapSet(_stakingCap); } function emergencyWithdraw() external { uint256 stakesAmount = _stakes[msg.sender]; stakedTotal = stakedTotal-(stakesAmount); _stakes[msg.sender] = 0; emit EmergencyWithdrawAdminDone(msg.sender,address(token), stakesAmount); token.transfer(msg.sender,stakesAmount); } function emergencyWithdrawAdmin() external onlyOwner { depositEnabled = false; uint256 amount = token.balanceOf(address(this)); emit EmergencyWithdrawAdminDone(msg.sender,address(token), amount); token.transfer(msg.sender,amount); } function setDepositEnabled() external onlyOwner { depositEnabled = !depositEnabled; emit DepositEnabledSet(depositEnabled); } function changeRewardAddress(address _address) external onlyOwner { require(_address != address(0), "Address should not be 0"); rewardAddress = _address; emit RewardAddressChanged(msg.sender,_address); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { 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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [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 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; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
* Requirements: - `amount` Amount to be staked/
function stake(uint256 amount) external { require(depositEnabled,"Deposits not enabled"); _stake(msg.sender, amount); }
13,410
[ 1, 15465, 30, 300, 1375, 8949, 68, 16811, 358, 506, 384, 9477, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 12, 11890, 5034, 3844, 13, 203, 565, 3903, 203, 565, 288, 203, 3639, 2583, 12, 323, 1724, 1526, 10837, 758, 917, 1282, 486, 3696, 8863, 203, 3639, 389, 334, 911, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x282CF833fF20DdB93384AbA81eE63847f4d8366A/sources/PopulationTracker.sol
Implement a withdraw function to avoid locking your LINK in the contract
function withdrawLink() external onlyOwner { LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require( link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer" ); }
11,131,451
[ 1, 5726, 279, 598, 9446, 445, 358, 4543, 18887, 3433, 22926, 316, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 2098, 1435, 3903, 1338, 5541, 288, 203, 3639, 4048, 1345, 1358, 1692, 273, 4048, 1345, 1358, 12, 5639, 1232, 1345, 1887, 10663, 203, 3639, 2583, 12, 203, 5411, 1692, 18, 13866, 12, 3576, 18, 15330, 16, 1692, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 3631, 203, 5411, 315, 3370, 358, 7412, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Dependency file: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT // pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol // pragma solidity >=0.6.2; // import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-periphery/contracts/interfaces/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; } // Dependency file: @openzeppelin/contracts/math/Math.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/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"); } } } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // Dependency file: contracts/interfaces/ISetToken.sol // pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } // Dependency file: contracts/interfaces/IBasicIssuanceModule.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity >=0.6.10; // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; interface IBasicIssuanceModule { function getRequiredComponentUnitsForIssue( ISetToken _setToken, uint256 _quantity ) external returns(address[] memory, uint256[] memory); function issue(ISetToken _setToken, uint256 _quantity, address _to) external; function redeem(ISetToken _token, uint256 _quantity, address _to) external; } // Dependency file: contracts/interfaces/IController.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // Dependency file: contracts/interfaces/IWETH.sol // pragma solidity >=0.6.10; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // Dependency file: contracts/lib/PreciseUnitMath.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // Dependency file: external/contracts/UniSushiV2Library.sol // pragma solidity >=0.5.0; // import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; library UniSushiV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // fetches and sorts the reserves for a pair function getReserves(address pair, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, '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(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // Root file: contracts/exchangeIssuance/ExchangeIssuance.sol /* Copyright 2021 Index Cooperative 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.10; // import { Address } from "@openzeppelin/contracts/utils/Address.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; // import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; // import { Math } from "@openzeppelin/contracts/math/Math.sol"; // import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import { IBasicIssuanceModule } from "contracts/interfaces/IBasicIssuanceModule.sol"; // import { IController } from "contracts/interfaces/IController.sol"; // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; // import { IWETH } from "contracts/interfaces/IWETH.sol"; // import { PreciseUnitMath } from "contracts/lib/PreciseUnitMath.sol"; // import { UniSushiV2Library } from "external/contracts/UniSushiV2Library.sol"; /** * @title ExchangeIssuance * @author Index Coop * * Contract for issuing and redeeming any SetToken using ETH or an ERC20 as the paying/receiving currency. * All swaps are done using the best price found on Uniswap or Sushiswap. * */ contract ExchangeIssuance is ReentrancyGuard { using Address for address payable; using SafeMath for uint256; using PreciseUnitMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISetToken; /* ============ Enums ============ */ enum Exchange { Uniswap, Sushiswap, None } /* ============ Constants ============= */ uint256 constant private MAX_UINT96 = 2**96 - 1; address constant public ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /* ============ State Variables ============ */ address public WETH; IUniswapV2Router02 public uniRouter; IUniswapV2Router02 public sushiRouter; address public immutable uniFactory; address public immutable sushiFactory; IController public immutable setController; IBasicIssuanceModule public immutable basicIssuanceModule; /* ============ Events ============ */ event ExchangeIssue( address indexed _recipient, // The recipient address of the issued SetTokens ISetToken indexed _setToken, // The issued SetToken IERC20 indexed _inputToken, // The address of the input asset(ERC20/ETH) used to issue the SetTokens uint256 _amountInputToken, // The amount of input tokens used for issuance uint256 _amountSetIssued // The amount of SetTokens received by the recipient ); event ExchangeRedeem( address indexed _recipient, // The recipient address which redeemed the SetTokens ISetToken indexed _setToken, // The redeemed SetToken IERC20 indexed _outputToken, // The address of output asset(ERC20/ETH) received by the recipient uint256 _amountSetRedeemed, // The amount of SetTokens redeemed for output tokens uint256 _amountOutputToken // The amount of output tokens received by the recipient ); event Refund( address indexed _recipient, // The recipient address which redeemed the SetTokens uint256 _refundAmount // The amount of ETH redunded to the recipient ); /* ============ Modifiers ============ */ modifier isSetToken(ISetToken _setToken) { require(setController.isSet(address(_setToken)), "ExchangeIssuance: INVALID SET"); _; } /* ============ Constructor ============ */ constructor( address _weth, address _uniFactory, IUniswapV2Router02 _uniRouter, address _sushiFactory, IUniswapV2Router02 _sushiRouter, IController _setController, IBasicIssuanceModule _basicIssuanceModule ) public { uniFactory = _uniFactory; uniRouter = _uniRouter; sushiFactory = _sushiFactory; sushiRouter = _sushiRouter; setController = _setController; basicIssuanceModule = _basicIssuanceModule; WETH = _weth; IERC20(WETH).safeApprove(address(uniRouter), PreciseUnitMath.maxUint256()); IERC20(WETH).safeApprove(address(sushiRouter), PreciseUnitMath.maxUint256()); } /* ============ Public Functions ============ */ /** * Runs all the necessary approval functions required for a given ERC20 token. * This function can be called when a new token is added to a SetToken during a * rebalance. * * @param _token Address of the token which needs approval */ function approveToken(IERC20 _token) public { _safeApprove(_token, address(uniRouter), MAX_UINT96); _safeApprove(_token, address(sushiRouter), MAX_UINT96); _safeApprove(_token, address(basicIssuanceModule), MAX_UINT96); } /* ============ External Functions ============ */ receive() external payable { // required for weth.withdraw() to work properly require(msg.sender == WETH, "ExchangeIssuance: Direct deposits not allowed"); } /** * Runs all the necessary approval functions required for a list of ERC20 tokens. * * @param _tokens Addresses of the tokens which need approval */ function approveTokens(IERC20[] calldata _tokens) external { for (uint256 i = 0; i < _tokens.length; i++) { approveToken(_tokens[i]); } } /** * Runs all the necessary approval functions required before issuing * or redeeming a SetToken. This function need to be called only once before the first time * this smart contract is used on any particular SetToken. * * @param _setToken Address of the SetToken being initialized */ function approveSetToken(ISetToken _setToken) isSetToken(_setToken) external { address[] memory components = _setToken.getComponents(); for (uint256 i = 0; i < components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); approveToken(IERC20(components[i])); } } /** * Issues SetTokens for an exact amount of input ERC20 tokens. * The ERC20 token must be approved by the sender to this contract. * * @param _setToken Address of the SetToken being issued * @param _inputToken Address of input token * @param _amountInput Amount of the input token / ether to spend * @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage. * * @return setTokenAmount Amount of SetTokens issued to the caller */ function issueSetForExactToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountInput, uint256 _minSetReceive ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _amountInput); uint256 amountEth = address(_inputToken) == WETH ? _amountInput : _swapTokenForWETH(_inputToken, _amountInput); uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, amountEth); emit ExchangeIssue(msg.sender, _setToken, _inputToken, _amountInput, setTokenAmount); return setTokenAmount; } /** * Issues SetTokens for an exact amount of input ether. * * @param _setToken Address of the SetToken to be issued * @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage. * * @return setTokenAmount Amount of SetTokens issued to the caller */ function issueSetForExactETH( ISetToken _setToken, uint256 _minSetReceive ) isSetToken(_setToken) external payable nonReentrant returns(uint256) { require(msg.value > 0, "ExchangeIssuance: INVALID INPUTS"); IWETH(WETH).deposit{value: msg.value}(); uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, msg.value); emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), msg.value, setTokenAmount); return setTokenAmount; } /** * Issues an exact amount of SetTokens for given amount of input ERC20 tokens. * The excess amount of tokens is returned in an equivalent amount of ether. * * @param _setToken Address of the SetToken to be issued * @param _inputToken Address of the input token * @param _amountSetToken Amount of SetTokens to issue * @param _maxAmountInputToken Maximum amount of input tokens to be used to issue SetTokens. The unused * input tokens are returned as ether. * * @return amountEthReturn Amount of ether returned to the caller */ function issueExactSetFromToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken, uint256 _maxAmountInputToken ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0 && _maxAmountInputToken > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _maxAmountInputToken); uint256 initETHAmount = address(_inputToken) == WETH ? _maxAmountInputToken : _swapTokenForWETH(_inputToken, _maxAmountInputToken); uint256 amountEthSpent = _issueExactSetFromWETH(_setToken, _amountSetToken, initETHAmount); uint256 amountEthReturn = initETHAmount.sub(amountEthSpent); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); (payable(msg.sender)).sendValue(amountEthReturn); } emit Refund(msg.sender, amountEthReturn); emit ExchangeIssue(msg.sender, _setToken, _inputToken, _maxAmountInputToken, _amountSetToken); return amountEthReturn; } /** * Issues an exact amount of SetTokens using a given amount of ether. * The excess ether is returned back. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to issue * * @return amountEthReturn Amount of ether returned to the caller */ function issueExactSetFromETH( ISetToken _setToken, uint256 _amountSetToken ) isSetToken(_setToken) external payable nonReentrant returns (uint256) { require(msg.value > 0 && _amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); IWETH(WETH).deposit{value: msg.value}(); uint256 amountEth = _issueExactSetFromWETH(_setToken, _amountSetToken, msg.value); uint256 amountEthReturn = msg.value.sub(amountEth); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); (payable(msg.sender)).sendValue(amountEthReturn); } emit Refund(msg.sender, amountEthReturn); emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), amountEth, _amountSetToken); return amountEthReturn; } /** * Redeems an exact amount of SetTokens for an ERC20 token. * The SetToken must be approved by the sender to this contract. * * @param _setToken Address of the SetToken being redeemed * @param _outputToken Address of output token * @param _amountSetToken Amount SetTokens to redeem * @param _minOutputReceive Minimum amount of output token to receive * * @return outputAmount Amount of output tokens sent to the caller */ function redeemExactSetForToken( ISetToken _setToken, IERC20 _outputToken, uint256 _amountSetToken, uint256 _minOutputReceive ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); ( uint256 totalEth, uint256[] memory amountComponents, Exchange[] memory exchanges ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); uint256 outputAmount; if (address(_outputToken) == WETH) { require(totalEth > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); outputAmount = _liquidateComponentsForWETH(components, amountComponents, exchanges); } else { (uint256 totalOutput, Exchange outTokenExchange, ) = _getMaxTokenForExactToken(totalEth, address(WETH), address(_outputToken)); require(totalOutput > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); uint256 outputEth = _liquidateComponentsForWETH(components, amountComponents, exchanges); outputAmount = _swapExactTokensForTokens(outTokenExchange, WETH, address(_outputToken), outputEth); } _outputToken.safeTransfer(msg.sender, outputAmount); emit ExchangeRedeem(msg.sender, _setToken, _outputToken, _amountSetToken, outputAmount); return outputAmount; } /** * Redeems an exact amount of SetTokens for ETH. * The SetToken must be approved by the sender to this contract. * * @param _setToken Address of the SetToken to be redeemed * @param _amountSetToken Amount of SetTokens to redeem * @param _minEthOut Minimum amount of ETH to receive * * @return amountEthOut Amount of ether sent to the caller */ function redeemExactSetForETH( ISetToken _setToken, uint256 _amountSetToken, uint256 _minEthOut ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); ( uint256 totalEth, uint256[] memory amountComponents, Exchange[] memory exchanges ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); require(totalEth > _minEthOut, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); uint256 amountEthOut = _liquidateComponentsForWETH(components, amountComponents, exchanges); IWETH(WETH).withdraw(amountEthOut); (payable(msg.sender)).sendValue(amountEthOut); emit ExchangeRedeem(msg.sender, _setToken, IERC20(ETH_ADDRESS), _amountSetToken, amountEthOut); return amountEthOut; } /** * Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token. * * @param _setToken Address of the SetToken being issued * @param _amountInput Amount of the input token to spend * @param _inputToken Address of input token. * * @return Estimated amount of SetTokens that will be received */ function getEstimatedIssueSetAmount( ISetToken _setToken, IERC20 _inputToken, uint256 _amountInput ) isSetToken(_setToken) external view returns (uint256) { require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS"); uint256 amountEth; if (address(_inputToken) != WETH) { // get max amount of WETH for the `_amountInput` amount of input tokens (amountEth, , ) = _getMaxTokenForExactToken(_amountInput, address(_inputToken), WETH); } else { amountEth = _amountInput; } address[] memory components = _setToken.getComponents(); (uint256 setIssueAmount, , ) = _getSetIssueAmountForETH(_setToken, components, amountEth); return setIssueAmount; } /** * Returns the amount of input ERC20 tokens required to issue an exact amount of SetTokens. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to issue * * @return Amount of tokens needed to issue specified amount of SetTokens */ function getAmountInToIssueExactSet( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken ) isSetToken(_setToken) external view returns(uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); (uint256 totalEth, , , , ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); if (address(_inputToken) == WETH) { return totalEth; } (uint256 tokenAmount, , ) = _getMinTokenForExactToken(totalEth, address(_inputToken), address(WETH)); return tokenAmount; } /** * Returns amount of output ERC20 tokens received upon redeeming a given amount of SetToken. * * @param _setToken Address of SetToken to be redeemed * @param _amountSetToken Amount of SetToken to be redeemed * @param _outputToken Address of output token * * @return Estimated amount of ether/erc20 that will be received */ function getAmountOutOnRedeemSet( ISetToken _setToken, address _outputToken, uint256 _amountSetToken ) isSetToken(_setToken) external view returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); (uint256 totalEth, , ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); if (_outputToken == WETH) { return totalEth; } // get maximum amount of tokens for totalEth amount of ETH (uint256 tokenAmount, , ) = _getMaxTokenForExactToken(totalEth, WETH, _outputToken); return tokenAmount; } /* ============ Internal Functions ============ */ /** * Sets a max approval limit for an ERC20 token, provided the current allowance * is less than the required allownce. * * @param _token Token to approve * @param _spender Spender address to approve */ function _safeApprove(IERC20 _token, address _spender, uint256 _requiredAllowance) internal { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _requiredAllowance) { _token.safeIncreaseAllowance(_spender, MAX_UINT96 - allowance); } } /** * Issues SetTokens for an exact amount of input WETH. * * @param _setToken Address of the SetToken being issued * @param _minSetReceive Minimum amount of index to receive * @param _totalEthAmount Total amount of WETH to be used to purchase the SetToken components * * @return setTokenAmount Amount of SetTokens issued */ function _issueSetForExactWETH(ISetToken _setToken, uint256 _minSetReceive, uint256 _totalEthAmount) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges ) = _getSetIssueAmountForETH(_setToken, components, _totalEthAmount); require(setIssueAmount > _minSetReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); for (uint256 i = 0; i < components.length; i++) { _swapExactTokensForTokens(exchanges[i], WETH, components[i], amountEthIn[i]); } basicIssuanceModule.issue(_setToken, setIssueAmount, msg.sender); return setIssueAmount; } /** * Issues an exact amount of SetTokens using WETH. * Acquires SetToken components at the best price accross uniswap and sushiswap. * Uses the acquired components to issue the SetTokens. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to be issued * @param _maxEther Max amount of ether that can be used to acquire the SetToken components * * @return totalEth Total amount of ether used to acquire the SetToken components */ function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 sumEth, , Exchange[] memory exchanges, uint256[] memory amountComponents, ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); require(sumEth <= _maxEther, "ExchangeIssuance: INSUFFICIENT_INPUT_AMOUNT"); uint256 totalEth = 0; for (uint256 i = 0; i < components.length; i++) { uint256 amountEth = _swapTokensForExactTokens(exchanges[i], WETH, components[i], amountComponents[i]); totalEth = totalEth.add(amountEth); } basicIssuanceModule.issue(_setToken, _amountSetToken, msg.sender); return totalEth; } /** * Redeems a given amount of SetToken. * * @param _setToken Address of the SetToken to be redeemed * @param _amount Amount of SetToken to be redeemed */ function _redeemExactSet(ISetToken _setToken, uint256 _amount) internal returns (uint256) { _setToken.safeTransferFrom(msg.sender, address(this), _amount); basicIssuanceModule.redeem(_setToken, _amount, address(this)); } /** * Liquidates a given list of SetToken components for WETH. * * @param _components An array containing the address of SetToken components * @param _amountComponents An array containing the amount of each SetToken component * @param _exchanges An array containing the exchange on which to liquidate the SetToken component * * @return Total amount of WETH received after liquidating all SetToken components */ function _liquidateComponentsForWETH(address[] memory _components, uint256[] memory _amountComponents, Exchange[] memory _exchanges) internal returns (uint256) { uint256 sumEth = 0; for (uint256 i = 0; i < _components.length; i++) { sumEth = _exchanges[i] == Exchange.None ? sumEth.add(_amountComponents[i]) : sumEth.add(_swapExactTokensForTokens(_exchanges[i], _components[i], WETH, _amountComponents[i])); } return sumEth; } /** * Gets the total amount of ether required for purchasing each component in a SetToken, * to enable the issuance of a given amount of SetTokens. * * @param _setToken Address of the SetToken to be issued * @param _components An array containing the addresses of the SetToken components * @param _amountSetToken Amount of SetToken to be issued * * @return sumEth The total amount of Ether reuired to issue the set * @return amountEthIn An array containing the amount of ether to purchase each component of the SetToken * @return exchanges An array containing the exchange on which to perform the purchase * @return amountComponents An array containing the amount of each SetToken component required for issuing the given * amount of SetToken * @return pairAddresses An array containing the pair addresses of ETH/component exchange pool */ function _getAmountETHForIssuance(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken) internal view returns ( uint256 sumEth, uint256[] memory amountEthIn, Exchange[] memory exchanges, uint256[] memory amountComponents, address[] memory pairAddresses ) { sumEth = 0; amountEthIn = new uint256[](_components.length); amountComponents = new uint256[](_components.length); exchanges = new Exchange[](_components.length); pairAddresses = new address[](_components.length); for (uint256 i = 0; i < _components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(_components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); // Get minimum amount of ETH to be spent to acquire the required amount of SetToken component uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i])); amountComponents[i] = uint256(unit).preciseMulCeil(_amountSetToken); (amountEthIn[i], exchanges[i], pairAddresses[i]) = _getMinTokenForExactToken(amountComponents[i], WETH, _components[i]); sumEth = sumEth.add(amountEthIn[i]); } return (sumEth, amountEthIn, exchanges, amountComponents, pairAddresses); } /** * Gets the total amount of ether returned from liquidating each component in a SetToken. * * @param _setToken Address of the SetToken to be redeemed * @param _components An array containing the addresses of the SetToken components * @param _amountSetToken Amount of SetToken to be redeemed * * @return sumEth The total amount of Ether that would be obtained from liquidating the SetTokens * @return amountComponents An array containing the amount of SetToken component to be liquidated * @return exchanges An array containing the exchange on which to liquidate the SetToken components */ function _getAmountETHForRedemption(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken) internal view returns (uint256, uint256[] memory, Exchange[] memory) { uint256 sumEth = 0; uint256 amountEth = 0; uint256[] memory amountComponents = new uint256[](_components.length); Exchange[] memory exchanges = new Exchange[](_components.length); for (uint256 i = 0; i < _components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(_components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i])); amountComponents[i] = unit.preciseMul(_amountSetToken); // get maximum amount of ETH received for a given amount of SetToken component (amountEth, exchanges[i], ) = _getMaxTokenForExactToken(amountComponents[i], _components[i], WETH); sumEth = sumEth.add(amountEth); } return (sumEth, amountComponents, exchanges); } /** * Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token. * * @param _setToken Address of the SetToken to be issued * @param _components An array containing the addresses of the SetToken components * @param _amountEth Total amount of ether available for the purchase of SetToken components * * @return setIssueAmount The max amount of SetTokens that can be issued * @return amountEthIn An array containing the amount ether required to purchase each SetToken component * @return exchanges An array containing the exchange on which to purchase the SetToken components */ function _getSetIssueAmountForETH(ISetToken _setToken, address[] memory _components, uint256 _amountEth) internal view returns (uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges) { uint256 sumEth; uint256[] memory unitAmountEthIn; uint256[] memory unitAmountComponents; address[] memory pairAddresses; ( sumEth, unitAmountEthIn, exchanges, unitAmountComponents, pairAddresses ) = _getAmountETHForIssuance(_setToken, _components, PreciseUnitMath.preciseUnit()); setIssueAmount = PreciseUnitMath.maxUint256(); amountEthIn = new uint256[](_components.length); for (uint256 i = 0; i < _components.length; i++) { amountEthIn[i] = unitAmountEthIn[i].mul(_amountEth).div(sumEth); uint256 amountComponent; if (exchanges[i] == Exchange.None) { amountComponent = amountEthIn[i]; } else { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(pairAddresses[i], WETH, _components[i]); amountComponent = UniSushiV2Library.getAmountOut(amountEthIn[i], reserveIn, reserveOut); } setIssueAmount = Math.min(amountComponent.preciseDiv(unitAmountComponents[i]), setIssueAmount); } return (setIssueAmount, amountEthIn, exchanges); } /** * Swaps a given amount of an ERC20 token for WETH for the best price on Uniswap/Sushiswap. * * @param _token Address of the ERC20 token to be swapped for WETH * @param _amount Amount of ERC20 token to be swapped * * @return Amount of WETH received after the swap */ function _swapTokenForWETH(IERC20 _token, uint256 _amount) internal returns (uint256) { (, Exchange exchange, ) = _getMaxTokenForExactToken(_amount, address(_token), WETH); IUniswapV2Router02 router = _getRouter(exchange); _safeApprove(_token, address(router), _amount); return _swapExactTokensForTokens(exchange, address(_token), WETH, _amount); } /** * Swap exact tokens for another token on a given DEX. * * @param _exchange The exchange on which to peform the swap * @param _tokenIn The address of the input token * @param _tokenOut The address of the output token * @param _amountIn The amount of input token to be spent * * @return The amount of output tokens */ function _swapExactTokensForTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountIn) internal returns (uint256) { if (_tokenIn == _tokenOut) { return _amountIn; } address[] memory path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; return _getRouter(_exchange).swapExactTokensForTokens(_amountIn, 0, path, address(this), block.timestamp)[1]; } /** * Swap tokens for exact amount of output tokens on a given DEX. * * @param _exchange The exchange on which to peform the swap * @param _tokenIn The address of the input token * @param _tokenOut The address of the output token * @param _amountOut The amount of output token required * * @return The amount of input tokens spent */ function _swapTokensForExactTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountOut) internal returns (uint256) { if (_tokenIn == _tokenOut) { return _amountOut; } address[] memory path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; return _getRouter(_exchange).swapTokensForExactTokens(_amountOut, PreciseUnitMath.maxUint256(), path, address(this), block.timestamp)[0]; } /** * Compares the amount of token required for an exact amount of another token across both exchanges, * and returns the min amount. * * @param _amountOut The amount of output token * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The min amount of tokenA required across both exchanges * @return The Exchange on which minimum amount of tokenA is required * @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB */ function _getMinTokenForExactToken(uint256 _amountOut, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) { if (_tokenA == _tokenB) { return (_amountOut, Exchange.None, ETH_ADDRESS); } uint256 maxIn = PreciseUnitMath.maxUint256() ; uint256 uniTokenIn = maxIn; uint256 sushiTokenIn = maxIn; address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB); if (uniswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB); // Prevent subtraction overflow by making sure pool reserves are greater than swap amount if (reserveOut > _amountOut) { uniTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut); } } address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB); if (sushiswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB); // Prevent subtraction overflow by making sure pool reserves are greater than swap amount if (reserveOut > _amountOut) { sushiTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut); } } // Fails if both the values are maxIn require(!(uniTokenIn == maxIn && sushiTokenIn == maxIn), "ExchangeIssuance: ILLIQUID_SET_COMPONENT"); return (uniTokenIn <= sushiTokenIn) ? (uniTokenIn, Exchange.Uniswap, uniswapPair) : (sushiTokenIn, Exchange.Sushiswap, sushiswapPair); } /** * Compares the amount of token received for an exact amount of another token across both exchanges, * and returns the max amount. * * @param _amountIn The amount of input token * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The max amount of tokens that can be received across both exchanges * @return The Exchange on which maximum amount of token can be received * @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB */ function _getMaxTokenForExactToken(uint256 _amountIn, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) { if (_tokenA == _tokenB) { return (_amountIn, Exchange.None, ETH_ADDRESS); } uint256 uniTokenOut = 0; uint256 sushiTokenOut = 0; address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB); if(uniswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB); uniTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut); } address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB); if(sushiswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB); sushiTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut); } // Fails if both the values are 0 require(!(uniTokenOut == 0 && sushiTokenOut == 0), "ExchangeIssuance: ILLIQUID_SET_COMPONENT"); return (uniTokenOut >= sushiTokenOut) ? (uniTokenOut, Exchange.Uniswap, uniswapPair) : (sushiTokenOut, Exchange.Sushiswap, sushiswapPair); } /** * Returns the pair address for on a given DEX. * * @param _factory The factory to address * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The pair address (Note: address(0) is returned by default if the pair is not available on that DEX) */ function _getPair(address _factory, address _tokenA, address _tokenB) internal view returns (address) { return IUniswapV2Factory(_factory).getPair(_tokenA, _tokenB); } /** * Returns the router address of a given exchange. * * @param _exchange The Exchange whose router address is needed * * @return IUniswapV2Router02 router of the given exchange */ function _getRouter(Exchange _exchange) internal view returns(IUniswapV2Router02) { return (_exchange == Exchange.Uniswap) ? uniRouter : sushiRouter; } }
* Redeems a given amount of SetToken. @param _setToken Address of the SetToken to be redeemed @param _amount Amount of SetToken to be redeemed/
function _redeemExactSet(ISetToken _setToken, uint256 _amount) internal returns (uint256) { _setToken.safeTransferFrom(msg.sender, address(this), _amount); basicIssuanceModule.redeem(_setToken, _amount, address(this)); }
2,571,890
[ 1, 426, 323, 7424, 279, 864, 3844, 434, 1000, 1345, 18, 225, 389, 542, 1345, 377, 5267, 434, 326, 1000, 1345, 358, 506, 283, 24903, 329, 225, 389, 8949, 4202, 16811, 434, 1000, 1345, 358, 506, 283, 24903, 329, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 266, 24903, 14332, 694, 12, 45, 694, 1345, 389, 542, 1345, 16, 2254, 5034, 389, 8949, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 389, 542, 1345, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 5337, 7568, 89, 1359, 3120, 18, 266, 24903, 24899, 542, 1345, 16, 389, 8949, 16, 1758, 12, 2211, 10019, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // https://etherscan.io/address/0xa478c2975ab1ea89e8196811f51a7b7ade33eb11#readContract contract UniswapETHDAIPoolMock is ERC20("DAI", "DAI") { uint256 private initBlock = block.number; // DAI / ETH function getReserves() public view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ) { return (1000000000 + uint112((block.number - initBlock) * 1000), 1000000, 0); } }
ERROR: type should be string, got " https:etherscan.io/address/0xa478c2975ab1ea89e8196811f51a7b7ade33eb11#readContract DAI / ETH"
contract UniswapETHDAIPoolMock is ERC20("DAI", "DAI") { uint256 private initBlock = block.number; function getReserves() public view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ) pragma solidity >=0.6.0 <0.8.0; { return (1000000000 + uint112((block.number - initBlock) * 1000), 1000000, 0); } }
14,035,425
[ 1, 4528, 30, 546, 414, 4169, 18, 1594, 19, 2867, 19, 20, 6995, 24, 8285, 71, 5540, 5877, 378, 21, 24852, 6675, 73, 28, 3657, 9470, 2499, 74, 10593, 69, 27, 70, 27, 2486, 3707, 24008, 2499, 896, 8924, 463, 18194, 342, 512, 2455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1351, 291, 91, 438, 1584, 44, 9793, 2579, 1371, 9865, 353, 4232, 39, 3462, 2932, 9793, 45, 3113, 315, 9793, 45, 7923, 288, 203, 565, 2254, 5034, 3238, 1208, 1768, 273, 1203, 18, 2696, 31, 203, 203, 565, 445, 31792, 264, 3324, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 17666, 389, 455, 6527, 20, 16, 203, 5411, 2254, 17666, 389, 455, 6527, 21, 16, 203, 5411, 2254, 1578, 389, 2629, 4921, 3024, 203, 3639, 262, 203, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 20, 411, 20, 18, 28, 18, 20, 31, 203, 565, 288, 203, 3639, 327, 261, 23899, 11706, 397, 2254, 17666, 12443, 2629, 18, 2696, 300, 1208, 1768, 13, 380, 4336, 3631, 15088, 16, 374, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * IOwnership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ interface IOwnership { /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool); /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address); } /** * Ownership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract Ownership is IOwnership { // Owner address internal owner; /** * Access is restricted to the current owner */ modifier only_owner() { require(msg.sender == owner); _; } /** * The publisher is the inital owner */ function Ownership() public { owner = msg.sender; } /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool) { return _account == owner; } /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address) { return owner; } } /** * ITransferableOwnership * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ interface ITransferableOwnership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) public; } /** * TransferableOwnership * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract TransferableOwnership is ITransferableOwnership, Ownership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) public only_owner { owner = _newOwner; } } /** * IAuthenticator * * Authenticator interface * * #created 15/10/2017 * #author Frank Bonnet */ interface IAuthenticator { /** * Authenticate * * Returns whether `_account` is authenticated or not * * @param _account The account to authenticate * @return whether `_account` is successfully authenticated */ function authenticate(address _account) public view returns (bool); } /** * IWhitelist * * Whitelist authentication interface * * #created 04/10/2017 * #author Frank Bonnet */ interface IWhitelist { /** * Returns whether an entry exists for `_account` * * @param _account The account to check * @return whether `_account` is has an entry in the whitelist */ function hasEntry(address _account) public view returns (bool); /** * Add `_account` to the whitelist * * If an account is currently disabled, the account is reenabled, otherwise * a new entry is created * * @param _account The account to add */ function add(address _account) public; /** * Remove `_account` from the whitelist * * Will not actually remove the entry but disable it by updating * the accepted record * * @param _account The account to remove */ function remove(address _account) public; } /** * Whitelist authentication list * * #created 04/10/2017 * #author Frank Bonnet */ contract Whitelist is IWhitelist, IAuthenticator, TransferableOwnership { struct Entry { uint datetime; bool accepted; uint index; } mapping(address => Entry) internal list; address[] internal listIndex; /** * Returns whether an entry exists for `_account` * * @param _account The account to check * @return whether `_account` is has an entry in the whitelist */ function hasEntry(address _account) public view returns (bool) { return listIndex.length > 0 && _account == listIndex[list[_account].index]; } /** * Add `_account` to the whitelist * * If an account is currently disabled, the account is reenabled, otherwise * a new entry is created * * @param _account The account to add */ function add(address _account) public only_owner { if (!hasEntry(_account)) { list[_account] = Entry( now, true, listIndex.push(_account) - 1); } else { Entry storage entry = list[_account]; if (!entry.accepted) { entry.accepted = true; entry.datetime = now; } } } /** * Remove `_account` from the whitelist * * Will not acctually remove the entry but disable it by updating * the accepted record * * @param _account The account to remove */ function remove(address _account) public only_owner { if (hasEntry(_account)) { Entry storage entry = list[_account]; entry.accepted = false; entry.datetime = now; } } /** * Authenticate * * Returns whether `_account` is on the whitelist * * @param _account The account to authenticate * @return whether `_account` is successfully authenticated */ function authenticate(address _account) public view returns (bool) { return list[_account].accepted; } }
* Whitelist authentication list #created 04/10/2017 #author Frank Bonnet/
contract Whitelist is IWhitelist, IAuthenticator, TransferableOwnership { } struct Entry { uint datetime; bool accepted; uint index; } mapping(address => Entry) internal list; address[] internal listIndex; function hasEntry(address _account) public view returns (bool) { return listIndex.length > 0 && _account == listIndex[list[_account].index]; } function add(address _account) public only_owner { if (!hasEntry(_account)) { list[_account] = Entry( now, true, listIndex.push(_account) - 1); Entry storage entry = list[_account]; if (!entry.accepted) { entry.accepted = true; entry.datetime = now; } } } function add(address _account) public only_owner { if (!hasEntry(_account)) { list[_account] = Entry( now, true, listIndex.push(_account) - 1); Entry storage entry = list[_account]; if (!entry.accepted) { entry.accepted = true; entry.datetime = now; } } } } else { function add(address _account) public only_owner { if (!hasEntry(_account)) { list[_account] = Entry( now, true, listIndex.push(_account) - 1); Entry storage entry = list[_account]; if (!entry.accepted) { entry.accepted = true; entry.datetime = now; } } } function remove(address _account) public only_owner { if (hasEntry(_account)) { Entry storage entry = list[_account]; entry.accepted = false; entry.datetime = now; } } function remove(address _account) public only_owner { if (hasEntry(_account)) { Entry storage entry = list[_account]; entry.accepted = false; entry.datetime = now; } } function authenticate(address _account) public view returns (bool) { return list[_account].accepted; } }
7,290,778
[ 1, 18927, 5107, 666, 2522, 16486, 19, 2163, 19, 31197, 2869, 478, 11500, 605, 265, 2758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3497, 7523, 353, 467, 18927, 16, 467, 18977, 16, 12279, 429, 5460, 12565, 288, 203, 203, 97, 203, 565, 1958, 3841, 288, 203, 3639, 2254, 3314, 31, 203, 3639, 1426, 8494, 31, 203, 3639, 2254, 770, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 516, 3841, 13, 2713, 666, 31, 203, 565, 1758, 8526, 2713, 666, 1016, 31, 203, 203, 203, 565, 445, 711, 1622, 12, 2867, 389, 4631, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 666, 1016, 18, 2469, 405, 374, 597, 389, 4631, 422, 666, 1016, 63, 1098, 63, 67, 4631, 8009, 1615, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 527, 12, 2867, 389, 4631, 13, 1071, 1338, 67, 8443, 288, 203, 3639, 309, 16051, 5332, 1622, 24899, 4631, 3719, 288, 203, 5411, 666, 63, 67, 4631, 65, 273, 3841, 12, 203, 7734, 2037, 16, 638, 16, 666, 1016, 18, 6206, 24899, 4631, 13, 300, 404, 1769, 203, 5411, 3841, 2502, 1241, 273, 666, 63, 67, 4631, 15533, 203, 5411, 309, 16051, 4099, 18, 23847, 13, 288, 203, 7734, 1241, 18, 23847, 273, 638, 31, 203, 7734, 1241, 18, 6585, 273, 2037, 31, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 565, 445, 527, 12, 2867, 389, 4631, 13, 1071, 1338, 67, 8443, 288, 203, 3639, 309, 16051, 5332, 1622, 24899, 4631, 3719, 288, 203, 5411, 666, 63, 67, 4631, 65, 273, 3841, 12, 203, 7734, 2037, 16, 638, 16, 666, 1016, 18, 6206, 24899, 4631, 13, 300, 404, 2 ]
// Base on aave-protocol // https://github.com/aave/aave-protocol/blob/e8d020e97/contracts/misc/ChainlinkProxyPriceProvider.sol // Changes: // - Upgrade to solidity 0.6.11 // - Remove fallbackOracle // - Store ethAddress (for potential WETH support) // - Add getETHPriceInAsset // - Followed solidity naming conventions // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import '@openzeppelin/contracts/access/Ownable.sol'; import './libraries/DSMath.sol'; import './interfaces/IPriceOracleGetter.sol'; import './interfaces/IChainlinkAggregator.sol'; /// @title ChainlinkProxyPriceProvider /// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator /// smart contracts as primary option /// - If the returned price by a Chainlink aggregator is <= 0, the transaction will be reverted /// - Can be owned by the governance system, allowed to add sources for assets, replace them contract ChainlinkProxyPriceProvider is IPriceOracleGetter, Ownable { using DSMath for uint256; event AssetSourceUpdated(address indexed asset, address indexed source); mapping(address => IChainlinkAggregator) private _assetsSources; address private _ethAddress; /// @notice Constructor /// @param assets The addresses of the assets /// @param sources The address of the source of each asset constructor(address[] memory assets, address[] memory sources) public { internalSetAssetsSources(assets, sources); } /// @notice External function called by the owner to set or replace sources of assets /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function setAssetSources(address[] calldata assets, address[] calldata sources) external onlyOwner { internalSetAssetsSources(assets, sources); } /// @notice Internal function to set the sources for each asset /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function internalSetAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH'); for (uint256 i = 0; i < assets.length; i++) { _assetsSources[assets[i]] = IChainlinkAggregator(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /// @notice Gets an asset price by address /// @param asset The asset address function getAssetPrice(address asset) public view override returns (uint256) { IChainlinkAggregator source = _assetsSources[asset]; if (asset == _ethAddress) { return 1 ether; } else { // Require the asset has registered source require(address(source) != address(0), 'SOURCE_IS_MISSING'); int256 price = IChainlinkAggregator(source).latestAnswer(); require(price > 0, 'INVALID_PRICE'); return uint256(price); } } /// @notice Gets ETH price in terms of asset, which is the reciprocal of getAssetPrice /// the number is not reounded by the asset actual number of decimal places /// expect proper rounding is done outside of this function and getAssetPrice /// returns number in WAD format /// @param asset The asset address function getETHPriceInAsset(address asset) external view override returns (uint256) { if (asset == _ethAddress) { return 1 ether; } else { uint256 assetPrice = getAssetPrice(asset); uint256 price = assetPrice.reciprocal(); require(price > 0, 'INVALID_PRICE'); return price; } } /// @notice Gets a list of prices from a list of assets addresses /// @param assets The list of assets addresses function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @notice Gets the address of the source for an asset address /// @param asset The address of the asset /// @return address The address of the source function getSourceOfAsset(address asset) external view returns (address) { return address(_assetsSources[asset]); } /// @notice Sets the ethAddress, in aave the ethAddress is a special representation for ETH, /// generalized to be configurable per system, can be for example WETH address /// @param ethAddress The address of ETH function setETHAddress(address ethAddress) external onlyOwner { require(ethAddress != address(0), 'ADDRESS_IS_ZERO'); _ethAddress = ethAddress; } /// @notice Gets the ethAddress /// @return address The ethAddress function getETHAddress() external view returns (address) { return _ethAddress; } }
@notice Gets ETH price in terms of asset, which is the reciprocal of getAssetPrice the number is not reounded by the asset actual number of decimal places expect proper rounding is done outside of this function and getAssetPrice returns number in WAD format @param asset The asset address
function getETHPriceInAsset(address asset) external view override returns (uint256) { if (asset == _ethAddress) { return 1 ether; uint256 assetPrice = getAssetPrice(asset); uint256 price = assetPrice.reciprocal(); require(price > 0, 'INVALID_PRICE'); return price; } }
1,028,454
[ 1, 3002, 512, 2455, 6205, 316, 6548, 434, 3310, 16, 1492, 353, 326, 5863, 30101, 434, 24689, 5147, 540, 326, 1300, 353, 486, 283, 12002, 635, 326, 3310, 3214, 1300, 434, 6970, 12576, 540, 4489, 5338, 13885, 353, 2731, 8220, 434, 333, 445, 471, 24689, 5147, 540, 1135, 1300, 316, 678, 1880, 740, 225, 3310, 1021, 3310, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 1584, 2500, 3057, 382, 6672, 12, 2867, 3310, 13, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 9406, 422, 389, 546, 1887, 13, 288, 203, 5411, 327, 404, 225, 2437, 31, 203, 5411, 2254, 5034, 3310, 5147, 273, 24689, 5147, 12, 9406, 1769, 203, 5411, 2254, 5034, 6205, 273, 3310, 5147, 18, 266, 3449, 30101, 5621, 203, 5411, 2583, 12, 8694, 405, 374, 16, 296, 9347, 67, 7698, 1441, 8284, 203, 203, 5411, 327, 6205, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; // In this example, calling 'Final.kill'would only trigger 'Base 2.kill' not reaching Base 1 contract owned { function owned() { owner = msg.sender; } address owner; } contract mortal is owned { function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract Base1 is mortal { function kill() { /* do cleanup 1 */ mortal.kill(); } } contract Base2 is mortal { function kill() { /* do cleanup 2 */ mortal.kill(); } } contract Final is Base1, Base2 { }
In this example, calling 'Final.kill'would only trigger 'Base 2.kill' not reaching Base 1
contract owned { address owner; function owned() { owner = msg.sender; } }
938,767
[ 1, 382, 333, 3454, 16, 4440, 296, 7951, 18, 16418, 11, 91, 1006, 1338, 3080, 296, 2171, 576, 18, 16418, 11, 486, 9287, 310, 3360, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16199, 288, 203, 202, 2867, 3410, 31, 202, 203, 202, 915, 16199, 1435, 288, 3410, 273, 1234, 18, 15330, 31, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x44B0E0b813371a1168c5d9d47DEA074c68116DfD/sources/home/hellwolf/Projects/superfluid/protocol-monorepo/packages/ethereum-contracts/contracts/agreements/InstantDistributionAgreementV1.sol
@dev IInstantDistributionAgreementV1.updateSubscription implementation before-hook callback update publisher data if the subscription exist and not approved, update the approved units amount update total units if the subscription exists and approved, update the pending units amount update pending subscription units of the publisher if the E_NO_SUBS, create it and then update the pending units amount create unallocated subscription adjust publisher's deposit and balances if subscription is pending update subscription data if necessary after-hook callback
function updateSubscription( ISuperfluidToken token, uint32 indexId, address subscriber, uint128 units, bytes calldata ctx ) external override returns(bytes memory newCtx) { _SubscriptionOperationVars memory vars; AgreementLibrary.CallbackInputs memory cbStates; bytes memory userData; address publisher; { ISuperfluid.Context memory context = AgreementLibrary.authorizeTokenAccess(token, ctx); userData = context.userData; publisher = context.msgSender; } ( vars.iId, vars.sId, vars.idata, vars.subscriptionExists, vars.sdata ) = _loadAllData(token, publisher, subscriber, indexId, false); cbStates = AgreementLibrary.createCallbackInputs( token, subscriber, vars.sId, ""); newCtx = ctx; if (vars.subscriptionExists) { cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_UPDATED_NOOP; vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx); cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_CREATED_NOOP; vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, newCtx); } if (vars.subscriptionExists && vars.sdata.subId != _UNALLOCATED_SUB_ID) { vars.idata.totalUnitsApproved = ( uint256(vars.idata.totalUnitsApproved) + uint256(units) - uint256(vars.sdata.units) ).toUint128(); token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata)); vars.idata.totalUnitsPending = ( uint256(vars.idata.totalUnitsPending) + uint256(units) - uint256(vars.sdata.units) ).toUint128(); token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata)); vars.sdata = SubscriptionData({ publisher: publisher, indexId: indexId, subId: _UNALLOCATED_SUB_ID, units: units, indexValue: vars.idata.indexValue }); token.createAgreement(vars.sId, _encodeSubscriptionData(vars.sdata)); vars.idata.totalUnitsPending = vars.idata.totalUnitsPending.add(units, "IDA: E_OVERFLOW"); token.updateAgreementData(vars.iId, _encodeIndexData(vars.idata)); } int256 balanceDelta = int256(vars.idata.indexValue - vars.sdata.indexValue) * int256(vars.sdata.units); if (vars.sdata.subId == _UNALLOCATED_SUB_ID) { _adjustPublisherDeposit(token, publisher, -balanceDelta); token.settleBalance(publisher, -balanceDelta); } if (vars.subscriptionExists) { vars.sdata.indexValue = vars.idata.indexValue; vars.sdata.units = units; token.updateAgreementData(vars.sId, _encodeSubscriptionData(vars.sdata)); } if (vars.subscriptionExists) { cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_UPDATED_NOOP; AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx); cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_CREATED_NOOP; AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx); } emit IndexUnitsUpdated(token, publisher, indexId, subscriber, units, userData); emit SubscriptionUnitsUpdated(token, subscriber, publisher, indexId, units, userData); }
14,280,118
[ 1, 45, 10675, 9003, 17420, 58, 21, 18, 2725, 6663, 4471, 1865, 17, 4476, 1348, 1089, 12855, 501, 309, 326, 4915, 1005, 471, 486, 20412, 16, 1089, 326, 20412, 4971, 3844, 1089, 2078, 4971, 309, 326, 4915, 1704, 471, 20412, 16, 1089, 326, 4634, 4971, 3844, 1089, 4634, 4915, 4971, 434, 326, 12855, 309, 326, 512, 67, 3417, 67, 8362, 55, 16, 752, 518, 471, 1508, 1089, 326, 4634, 4971, 3844, 752, 640, 28172, 4915, 5765, 12855, 1807, 443, 1724, 471, 324, 26488, 309, 4915, 353, 4634, 1089, 4915, 501, 309, 4573, 1839, 17, 4476, 1348, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 6663, 12, 203, 3639, 467, 8051, 2242, 1911, 1345, 1147, 16, 203, 3639, 2254, 1578, 770, 548, 16, 203, 3639, 1758, 9467, 16, 203, 3639, 2254, 10392, 4971, 16, 203, 3639, 1731, 745, 892, 1103, 203, 565, 262, 203, 3639, 3903, 3849, 203, 3639, 1135, 12, 3890, 3778, 394, 6442, 13, 203, 565, 288, 203, 3639, 389, 6663, 2988, 5555, 3778, 4153, 31, 203, 3639, 5495, 10606, 9313, 18, 2428, 10059, 3778, 2875, 7629, 31, 203, 3639, 1731, 3778, 13530, 31, 203, 3639, 1758, 12855, 31, 203, 3639, 288, 203, 5411, 467, 8051, 2242, 1911, 18, 1042, 3778, 819, 273, 5495, 10606, 9313, 18, 22488, 1345, 1862, 12, 2316, 16, 1103, 1769, 203, 5411, 13530, 273, 819, 18, 1355, 751, 31, 203, 5411, 12855, 273, 819, 18, 3576, 12021, 31, 203, 3639, 289, 203, 203, 3639, 261, 203, 5411, 4153, 18, 77, 548, 16, 203, 5411, 4153, 18, 87, 548, 16, 203, 5411, 4153, 18, 350, 396, 16, 203, 5411, 4153, 18, 11185, 4002, 16, 203, 5411, 4153, 18, 87, 892, 203, 3639, 262, 273, 389, 945, 1595, 751, 12, 2316, 16, 12855, 16, 9467, 16, 770, 548, 16, 629, 1769, 203, 203, 3639, 2875, 7629, 273, 5495, 10606, 9313, 18, 2640, 2428, 10059, 12, 203, 5411, 1147, 16, 203, 5411, 9467, 16, 203, 5411, 4153, 18, 87, 548, 16, 203, 5411, 1408, 1769, 203, 3639, 394, 6442, 273, 1103, 31, 203, 203, 3639, 309, 261, 4699, 18, 11185, 4002, 13, 288, 203, 5411, 2875, 7629, 18, 2135, 556, 5775, 273, 2 ]
./partial_match/1/0xB2A36419d07192Ac8D8CC40594C471F29e074e46/sources/contracts/OKLGFaaSTimePricing.sol
* Returns the latest ETH/USD price with returned value at 18 decimals/
function _getLatestETHPrice() internal view returns (uint256) { uint8 decimals = priceFeed.decimals(); (, int256 price, , , ) = priceFeed.latestRoundData(); return uint256(price) * (10**18 / 10**decimals); }
4,228,573
[ 1, 1356, 326, 4891, 512, 2455, 19, 3378, 40, 6205, 598, 2106, 460, 622, 6549, 15105, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 588, 18650, 1584, 2500, 3057, 1435, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 28, 15105, 273, 6205, 8141, 18, 31734, 5621, 203, 565, 261, 16, 509, 5034, 6205, 16, 269, 269, 262, 273, 6205, 8141, 18, 13550, 11066, 751, 5621, 203, 565, 327, 2254, 5034, 12, 8694, 13, 380, 261, 2163, 636, 2643, 342, 1728, 636, 31734, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.0; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/Buying.sol"; contract TestBuying { // The address of the buying contract to be tested Buying buying = Buying(DeployedAddresses.Buying()); // The id of the pet that will be used for testing uint expectedPetId = 8; //The expected owner of adopted pet is this contract address expectedAdopter = address(this); // Testing the adopt() function function testUserCanAdoptPet() public { uint returnedId = buying.buy(expectedPetId); Assert.equal(returnedId, expectedPetId, "Buying of the expected merch should match what is returned."); } // Testing retrieval of a single pet's owner function testGetAdopterAddressByPetId() public { address adopter = buying.buyers(expectedPetId); Assert.equal(adopter, expectedAdopter, "Owner of the expected pet should be this contract"); } // Testing retrieval of all pet owners function testGetAdopterAddressByPetIdInArray() public { // Store adopters in memory rather than contract's storage address[16] memory adopters = buying.getBuyers(); Assert.equal(adopters[expectedPetId], expectedAdopter, "Owner of the expected pet should be this contract"); } }
Testing retrieval of a single pet's owner
function testGetAdopterAddressByPetId() public { address adopter = buying.buyers(expectedPetId); Assert.equal(adopter, expectedAdopter, "Owner of the expected pet should be this contract"); }
2,531,816
[ 1, 22218, 22613, 434, 279, 2202, 293, 278, 1807, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 967, 1871, 3838, 264, 1887, 858, 52, 278, 548, 1435, 1071, 288, 203, 203, 3639, 1758, 1261, 3838, 264, 273, 30143, 310, 18, 70, 9835, 414, 12, 3825, 52, 278, 548, 1769, 203, 203, 565, 5452, 18, 9729, 12, 361, 3838, 264, 16, 2665, 1871, 3838, 264, 16, 315, 5541, 434, 326, 2665, 293, 278, 1410, 506, 333, 6835, 8863, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x2072d16c15978a7050a93b62a315e1caa13c6c27 //Contract name: TaskManager //Balance: 0.468635899121845162 Ether //Verification Date: 5/11/2018 //Transacion Count: 26 // CODE STARTS HERE pragma solidity ^0.4.23; /******* USING Registry ************************** Gives the inherting contract access to: .addressOf(bytes32): returns current address mapped to the name. [modifier] .fromOwner(): requires the sender is owner. *************************************************/ // Returned by .getRegistry() interface IRegistry { function owner() external view returns (address _addr); function addressOf(bytes32 _name) external view returns (address _addr); } contract UsingRegistry { IRegistry private registry; modifier fromOwner(){ require(msg.sender == getOwner()); _; } constructor(address _registry) public { require(_registry != 0); registry = IRegistry(_registry); } function addressOf(bytes32 _name) internal view returns(address _addr) { return registry.addressOf(_name); } function getOwner() public view returns (address _addr) { return registry.owner(); } function getRegistry() public view returns (IRegistry _addr) { return registry; } } /******* USING ADMIN *********************** Gives the inherting contract access to: .getAdmin(): returns the current address of the admin [modifier] .fromAdmin: requires the sender is the admin *************************************************/ contract UsingAdmin is UsingRegistry { constructor(address _registry) UsingRegistry(_registry) public {} modifier fromAdmin(){ require(msg.sender == getAdmin()); _; } function getAdmin() public constant returns (address _addr) { return addressOf("ADMIN"); } } /******* USING MONARCHYCONTROLLER ************************** Gives the inherting contract access to: .getMonarchyController(): returns current IMC instance [modifier] .fromMonarchyController(): requires the sender is current MC. *************************************************/ // Returned by .getMonarchyController() interface IMonarchyController { function refreshGames() external returns (uint _numGamesEnded, uint _feesSent); function startDefinedGame(uint _index) external payable returns (address _game); function getFirstStartableIndex() external view returns (uint _index); function getNumEndableGames() external view returns (uint _count); function getAvailableFees() external view returns (uint _feesAvailable); function getInitialPrize(uint _index) external view returns (uint); function getIsStartable(uint _index) external view returns (bool); } contract UsingMonarchyController is UsingRegistry { constructor(address _registry) UsingRegistry(_registry) public {} modifier fromMonarchyController(){ require(msg.sender == address(getMonarchyController())); _; } function getMonarchyController() public view returns (IMonarchyController) { return IMonarchyController(addressOf("MONARCHY_CONTROLLER")); } } /******* USING TREASURY ************************** Gives the inherting contract access to: .getTreasury(): returns current ITreasury instance [modifier] .fromTreasury(): requires the sender is current Treasury *************************************************/ // Returned by .getTreasury() interface ITreasury { function issueDividend() external returns (uint _profits); function profitsSendable() external view returns (uint _profits); } contract UsingTreasury is UsingRegistry { constructor(address _registry) UsingRegistry(_registry) public {} modifier fromTreasury(){ require(msg.sender == address(getTreasury())); _; } function getTreasury() public view returns (ITreasury) { return ITreasury(addressOf("TREASURY")); } } /* Exposes the following internal methods: - _useFromDailyLimit(uint) - _setDailyLimit(uint) - getDailyLimit() - getDailyLimitUsed() - getDailyLimitUnused() */ contract HasDailyLimit { // squeeze all vars into one storage slot. struct DailyLimitVars { uint112 dailyLimit; // Up to 5e15 * 1e18. uint112 usedToday; // Up to 5e15 * 1e18. uint32 lastDay; // Up to the year 11,000,000 AD } DailyLimitVars private vars; uint constant MAX_ALLOWED = 2**112 - 1; constructor(uint _limit) public { _setDailyLimit(_limit); } // Sets the daily limit. function _setDailyLimit(uint _limit) internal { require(_limit <= MAX_ALLOWED); vars.dailyLimit = uint112(_limit); } // Uses the requested amount if its within limit. Or throws. // You should use getDailyLimitRemaining() before calling this. function _useFromDailyLimit(uint _amount) internal { uint _remaining = updateAndGetRemaining(); require(_amount <= _remaining); vars.usedToday += uint112(_amount); } // If necessary, resets the day's usage. // Then returns the amount remaining for today. function updateAndGetRemaining() private returns (uint _amtRemaining) { if (today() > vars.lastDay) { vars.usedToday = 0; vars.lastDay = today(); } uint112 _usedToday = vars.usedToday; uint112 _dailyLimit = vars.dailyLimit; // This could be negative if _dailyLimit was reduced. return uint(_usedToday >= _dailyLimit ? 0 : _dailyLimit - _usedToday); } // Returns the current day. function today() private view returns (uint32) { return uint32(block.timestamp / 1 days); } ///////////////////////////////////////////////////////////////// ////////////// PUBLIC VIEWS ///////////////////////////////////// ///////////////////////////////////////////////////////////////// function getDailyLimit() public view returns (uint) { return uint(vars.dailyLimit); } function getDailyLimitUsed() public view returns (uint) { return uint(today() > vars.lastDay ? 0 : vars.usedToday); } function getDailyLimitRemaining() public view returns (uint) { uint _used = getDailyLimitUsed(); return uint(_used >= vars.dailyLimit ? 0 : vars.dailyLimit - _used); } } /** This is a simple class that maintains a doubly linked list of addresses it has seen. Addresses can be added and removed from the set, and a full list of addresses can be obtained. Methods: - [fromOwner] .add() - [fromOwner] .remove() Views: - .size() - .has() - .addresses() */ contract AddressSet { struct Entry { // Doubly linked list bool exists; address next; address prev; } mapping (address => Entry) public entries; address public owner; modifier fromOwner() { require(msg.sender==owner); _; } // Constructor sets the owner. constructor(address _owner) public { owner = _owner; } /******************************************************/ /*************** OWNER METHODS ************************/ /******************************************************/ function add(address _address) fromOwner public returns (bool _didCreate) { // Do not allow the adding of HEAD. if (_address == address(0)) return; Entry storage entry = entries[_address]; // If already exists, do nothing. Otherwise set it. if (entry.exists) return; else entry.exists = true; // Replace first entry with this one. // Before: HEAD <-> X <-> Y // After: HEAD <-> THIS <-> X <-> Y // do: THIS.NEXT = [0].next; [0].next.prev = THIS; [0].next = THIS; THIS.prev = 0; Entry storage HEAD = entries[0x0]; entry.next = HEAD.next; entries[HEAD.next].prev = _address; HEAD.next = _address; return true; } function remove(address _address) fromOwner public returns (bool _didExist) { // Do not allow the removal of HEAD. if (_address == address(0)) return; Entry storage entry = entries[_address]; // If it doesn't exist already, there is nothing to do. if (!entry.exists) return; // Stitch together next and prev, delete entry. // Before: X <-> THIS <-> Y // After: X <-> Y // do: THIS.next.prev = this.prev; THIS.prev.next = THIS.next; entries[entry.prev].next = entry.next; entries[entry.next].prev = entry.prev; delete entries[_address]; return true; } /******************************************************/ /*************** PUBLIC VIEWS *************************/ /******************************************************/ function size() public view returns (uint _size) { // Loop once to get the total count. Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _curEntry = entries[_curEntry.next]; _size++; } return _size; } function has(address _address) public view returns (bool _exists) { return entries[_address].exists; } function addresses() public view returns (address[] _addresses) { // Populate names and addresses uint _size = size(); _addresses = new address[](_size); // Iterate forward through all entries until the end. uint _i = 0; Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _addresses[_i] = _curEntry.next; _curEntry = entries[_curEntry.next]; _i++; } return _addresses; } } /** This is a simple class that maintains a doubly linked list of address => uint amounts. Address balances can be added to or removed from via add() and subtract(). All balances can be obtain by calling balances(). If an address has a 0 amount, it is removed from the Ledger. Note: THIS DOES NOT TEST FOR OVERFLOWS, but it's safe to use to track Ether balances. Public methods: - [fromOwner] add() - [fromOwner] subtract() Public views: - total() - size() - balanceOf() - balances() - entries() [to manually iterate] */ contract Ledger { uint public total; // Total amount in Ledger struct Entry { // Doubly linked list tracks amount per address uint balance; address next; address prev; } mapping (address => Entry) public entries; address public owner; modifier fromOwner() { require(msg.sender==owner); _; } // Constructor sets the owner constructor(address _owner) public { owner = _owner; } /******************************************************/ /*************** OWNER METHODS ************************/ /******************************************************/ function add(address _address, uint _amt) fromOwner public { if (_address == address(0) || _amt == 0) return; Entry storage entry = entries[_address]; // If new entry, replace first entry with this one. if (entry.balance == 0) { entry.next = entries[0x0].next; entries[entries[0x0].next].prev = _address; entries[0x0].next = _address; } // Update stats. total += _amt; entry.balance += _amt; } function subtract(address _address, uint _amt) fromOwner public returns (uint _amtRemoved) { if (_address == address(0) || _amt == 0) return; Entry storage entry = entries[_address]; uint _maxAmt = entry.balance; if (_maxAmt == 0) return; if (_amt >= _maxAmt) { // Subtract the max amount, and delete entry. total -= _maxAmt; entries[entry.prev].next = entry.next; entries[entry.next].prev = entry.prev; delete entries[_address]; return _maxAmt; } else { // Subtract the amount from entry. total -= _amt; entry.balance -= _amt; return _amt; } } /******************************************************/ /*************** PUBLIC VIEWS *************************/ /******************************************************/ function size() public view returns (uint _size) { // Loop once to get the total count. Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _curEntry = entries[_curEntry.next]; _size++; } return _size; } function balanceOf(address _address) public view returns (uint _balance) { return entries[_address].balance; } function balances() public view returns (address[] _addresses, uint[] _balances) { // Populate names and addresses uint _size = size(); _addresses = new address[](_size); _balances = new uint[](_size); uint _i = 0; Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _addresses[_i] = _curEntry.next; _balances[_i] = entries[_curEntry.next].balance; _curEntry = entries[_curEntry.next]; _i++; } return (_addresses, _balances); } } /** A simple class that manages bankroll, and maintains collateral. This class only ever sends profits the Treasury. No exceptions. - Anybody can add funding (according to whitelist) - Anybody can tell profits (balance - (funding + collateral)) to go to Treasury. - Anyone can remove their funding, so long as balance >= collateral. - Whitelist is managed by getWhitelistOwner() -- typically Admin. Exposes the following: Public Methods - addBankroll - removeBankroll - sendProfits Public Views - getCollateral - profits - profitsSent - profitsTotal - bankroll - bankrollAvailable - bankrolledBy - bankrollerTable */ contract Bankrollable is UsingTreasury { // How much profits have been sent. uint public profitsSent; // Ledger keeps track of who has bankrolled us, and for how much Ledger public ledger; // This is a copy of ledger.total(), to save gas in .bankrollAvailable() uint public bankroll; // This is the whitelist of who can call .addBankroll() AddressSet public whitelist; modifier fromWhitelistOwner(){ require(msg.sender == getWhitelistOwner()); _; } event BankrollAdded(uint time, address indexed bankroller, uint amount, uint bankroll); event BankrollRemoved(uint time, address indexed bankroller, uint amount, uint bankroll); event ProfitsSent(uint time, address indexed treasury, uint amount); event AddedToWhitelist(uint time, address indexed addr, address indexed wlOwner); event RemovedFromWhitelist(uint time, address indexed addr, address indexed wlOwner); // Constructor creates the ledger and whitelist, with self as owner. constructor(address _registry) UsingTreasury(_registry) public { ledger = new Ledger(this); whitelist = new AddressSet(this); } /*****************************************************/ /************** WHITELIST MGMT ***********************/ /*****************************************************/ function addToWhitelist(address _addr) fromWhitelistOwner public { bool _didAdd = whitelist.add(_addr); if (_didAdd) emit AddedToWhitelist(now, _addr, msg.sender); } function removeFromWhitelist(address _addr) fromWhitelistOwner public { bool _didRemove = whitelist.remove(_addr); if (_didRemove) emit RemovedFromWhitelist(now, _addr, msg.sender); } /*****************************************************/ /************** PUBLIC FUNCTIONS *********************/ /*****************************************************/ // Bankrollable contracts should be payable (to receive revenue) function () public payable {} // Increase funding by whatever value is sent function addBankroll() public payable { require(whitelist.size()==0 || whitelist.has(msg.sender)); ledger.add(msg.sender, msg.value); bankroll = ledger.total(); emit BankrollAdded(now, msg.sender, msg.value, bankroll); } // Removes up to _amount from Ledger, and sends it to msg.sender._callbackFn function removeBankroll(uint _amount, string _callbackFn) public returns (uint _recalled) { // cap amount at the balance minus collateral, or nothing at all. address _bankroller = msg.sender; uint _collateral = getCollateral(); uint _balance = address(this).balance; uint _available = _balance > _collateral ? _balance - _collateral : 0; if (_amount > _available) _amount = _available; // Try to remove _amount from ledger, get actual _amount removed. _amount = ledger.subtract(_bankroller, _amount); bankroll = ledger.total(); if (_amount == 0) return; bytes4 _sig = bytes4(keccak256(_callbackFn)); require(_bankroller.call.value(_amount)(_sig)); emit BankrollRemoved(now, _bankroller, _amount, bankroll); return _amount; } // Send any excess profits to treasury. function sendProfits() public returns (uint _profits) { int _p = profits(); if (_p <= 0) return; _profits = uint(_p); profitsSent += _profits; // Send profits to Treasury address _tr = getTreasury(); require(_tr.call.value(_profits)()); emit ProfitsSent(now, _tr, _profits); } /*****************************************************/ /************** PUBLIC VIEWS *************************/ /*****************************************************/ // Function must be overridden by inheritors to ensure collateral is kept. function getCollateral() public view returns (uint _amount); // Function must be overridden by inheritors to enable whitelist control. function getWhitelistOwner() public view returns (address _addr); // Profits are the difference between balance and threshold function profits() public view returns (int _profits) { int _balance = int(address(this).balance); int _threshold = int(bankroll + getCollateral()); return _balance - _threshold; } // How profitable this contract is, overall function profitsTotal() public view returns (int _profits) { return int(profitsSent) + profits(); } // Returns the amount that can currently be bankrolled. // - 0 if balance < collateral // - If profits: full bankroll // - If no profits: remaning bankroll: balance - collateral function bankrollAvailable() public view returns (uint _amount) { uint _balance = address(this).balance; uint _bankroll = bankroll; uint _collat = getCollateral(); // Balance is below collateral! if (_balance <= _collat) return 0; // No profits, but we have a balance over collateral. else if (_balance < _collat + _bankroll) return _balance - _collat; // Profits. Return only _bankroll else return _bankroll; } function bankrolledBy(address _addr) public view returns (uint _amount) { return ledger.balanceOf(_addr); } function bankrollerTable() public view returns (address[], uint[]) { return ledger.balances(); } } /* This is a simple class that pays anybody to execute methods on other contracts. The reward amounts are configurable by the Admin, with some hard limits to prevent the Admin from pilfering. The contract has a DailyLimit, so even if the Admin is compromised, the contract cannot be drained. TaskManager is Bankrollable, meaning it can accept bankroll from the Treasury (and have it recalled). However, it will never generate profits. On rare occasion, new funds will need to be added to ensure rewards can be paid. This class is divided into sections that pay rewards for a specific contract or set of contracts. Any time a new contract is added to the system that requires Tasks, this file will be updated and redeployed. */ interface _IBankrollable { function sendProfits() external returns (uint _profits); function profits() external view returns (int _profits); } contract TaskManager is HasDailyLimit, Bankrollable, UsingAdmin, UsingMonarchyController { uint constant public version = 1; uint public totalRewarded; // Number of basis points to reward caller. // 1 = .01%, 10 = .1%, 100 = 1%. Capped at .1%. uint public issueDividendRewardBips; // Number of basis points to reward caller. // 1 = .01%, 10 = .1%, 100 = 1%. Capped at 1%. uint public sendProfitsRewardBips; // How much to pay for games to start and end. // These values are capped at 1 Ether. uint public monarchyStartReward; uint public monarchyEndReward; event Created(uint time); event DailyLimitChanged(uint time, address indexed owner, uint newValue); // admin events event IssueDividendRewardChanged(uint time, address indexed admin, uint newValue); event SendProfitsRewardChanged(uint time, address indexed admin, uint newValue); event MonarchyRewardsChanged(uint time, address indexed admin, uint startReward, uint endReward); // base events event TaskError(uint time, address indexed caller, string msg); event RewardSuccess(uint time, address indexed caller, uint reward); event RewardFailure(uint time, address indexed caller, uint reward, string msg); // task events event IssueDividendSuccess(uint time, address indexed treasury, uint profitsSent); event SendProfitsSuccess(uint time, address indexed bankrollable, uint profitsSent); event MonarchyGameStarted(uint time, address indexed addr, uint initialPrize); event MonarchyGamesRefreshed(uint time, uint numEnded, uint feesCollected); // Construct sets the registry and instantiates inherited classes. constructor(address _registry) public HasDailyLimit(1 ether) Bankrollable(_registry) UsingAdmin(_registry) UsingMonarchyController(_registry) { emit Created(now); } /////////////////////////////////////////////////////////////////// ////////// OWNER FUNCTIONS //////////////////////////////////////// /////////////////////////////////////////////////////////////////// function setDailyLimit(uint _amount) public fromOwner { _setDailyLimit(_amount); emit DailyLimitChanged(now, msg.sender, _amount); } /////////////////////////////////////////////////////////////////// ////////// ADMIN FUNCTIONS //////////////////////////////////////// /////////////////////////////////////////////////////////////////// function setIssueDividendReward(uint _bips) public fromAdmin { require(_bips <= 10); issueDividendRewardBips = _bips; emit IssueDividendRewardChanged(now, msg.sender, _bips); } function setSendProfitsReward(uint _bips) public fromAdmin { require(_bips <= 100); sendProfitsRewardBips = _bips; emit SendProfitsRewardChanged(now, msg.sender, _bips); } function setMonarchyRewards(uint _startReward, uint _endReward) public fromAdmin { require(_startReward <= 1 ether); require(_endReward <= 1 ether); monarchyStartReward = _startReward; monarchyEndReward = _endReward; emit MonarchyRewardsChanged(now, msg.sender, _startReward, _endReward); } /////////////////////////////////////////////////////////////////// ////////// ISSUE DIVIDEND TASK //////////////////////////////////// /////////////////////////////////////////////////////////////////// function doIssueDividend() public returns (uint _reward, uint _profits) { // get amount of profits ITreasury _tr = getTreasury(); _profits = _tr.profitsSendable(); // quit if no profits to send. if (_profits == 0) { _taskError("No profits to send."); return; } // call .issueDividend(), use return value to compute _reward _profits = _tr.issueDividend(); if (_profits == 0) { _taskError("No profits were sent."); return; } else { emit IssueDividendSuccess(now, address(_tr), _profits); } // send reward _reward = (_profits * issueDividendRewardBips) / 10000; _sendReward(_reward); } // Returns reward and profits function issueDividendReward() public view returns (uint _reward, uint _profits) { _profits = getTreasury().profitsSendable(); _reward = _cappedReward((_profits * issueDividendRewardBips) / 10000); } /////////////////////////////////////////////////////////////////// ////////// SEND PROFITS TASKS ///////////////////////////////////// /////////////////////////////////////////////////////////////////// function doSendProfits(address _bankrollable) public returns (uint _reward, uint _profits) { // Call .sendProfits(). Look for Treasury balance to change. ITreasury _tr = getTreasury(); uint _oldTrBalance = address(_tr).balance; _IBankrollable(_bankrollable).sendProfits(); uint _newTrBalance = address(_tr).balance; // Quit if no profits. Otherwise compute profits. if (_newTrBalance <= _oldTrBalance) { _taskError("No profits were sent."); return; } else { _profits = _newTrBalance - _oldTrBalance; emit SendProfitsSuccess(now, _bankrollable, _profits); } // Cap reward to current balance (or send will fail) _reward = (_profits * sendProfitsRewardBips) / 10000; _sendReward(_reward); } // Returns an estimate of profits to send, and reward. function sendProfitsReward(address _bankrollable) public view returns (uint _reward, uint _profits) { int _p = _IBankrollable(_bankrollable).profits(); if (_p <= 0) return; _profits = uint(_p); _reward = _cappedReward((_profits * sendProfitsRewardBips) / 10000); } /////////////////////////////////////////////////////////////////// ////////// MONARCHY TASKS ///////////////////////////////////////// /////////////////////////////////////////////////////////////////// // Try to start monarchy game, reward upon success. function startMonarchyGame(uint _index) public { // Don't bother trying if it's not startable IMonarchyController _mc = getMonarchyController(); if (!_mc.getIsStartable(_index)){ _taskError("Game is not currently startable."); return; } // Try to start the game. This may fail. address _game = _mc.startDefinedGame(_index); if (_game == address(0)) { _taskError("MonarchyConroller.startDefinedGame() failed."); return; } else { emit MonarchyGameStarted(now, _game, _mc.getInitialPrize(_index)); } // Reward _sendReward(monarchyStartReward); } // Return the _reward and _index of the first startable MonarchyGame function startMonarchyGameReward() public view returns (uint _reward, uint _index) { IMonarchyController _mc = getMonarchyController(); _index = _mc.getFirstStartableIndex(); if (_index > 0) _reward = _cappedReward(monarchyStartReward); } // Invoke .refreshGames() and pay reward on number of games ended. function refreshMonarchyGames() public { // do the call uint _numGamesEnded; uint _feesCollected; (_numGamesEnded, _feesCollected) = getMonarchyController().refreshGames(); emit MonarchyGamesRefreshed(now, _numGamesEnded, _feesCollected); if (_numGamesEnded == 0) { _taskError("No games ended."); } else { _sendReward(_numGamesEnded * monarchyEndReward); } } // Return a reward for each MonarchyGame that will end function refreshMonarchyGamesReward() public view returns (uint _reward, uint _numEndable) { IMonarchyController _mc = getMonarchyController(); _numEndable = _mc.getNumEndableGames(); _reward = _cappedReward(_numEndable * monarchyEndReward); } /////////////////////////////////////////////////////////////////////// /////////////////// PRIVATE FUNCTIONS ///////////////////////////////// /////////////////////////////////////////////////////////////////////// // Called when task is unable to execute. function _taskError(string _msg) private { emit TaskError(now, msg.sender, _msg); } // Sends a capped amount of _reward to the msg.sender, and emits proper event. function _sendReward(uint _reward) private { // Limit the reward to balance or dailyLimitRemaining uint _amount = _cappedReward(_reward); if (_reward > 0 && _amount == 0) { emit RewardFailure(now, msg.sender, _amount, "Not enough funds, or daily limit reached."); return; } // Attempt to send it (even if _reward was 0) if (msg.sender.call.value(_amount)()) { _useFromDailyLimit(_amount); totalRewarded += _amount; emit RewardSuccess(now, msg.sender, _amount); } else { emit RewardFailure(now, msg.sender, _amount, "Reward rejected by recipient (out of gas, or revert)."); } } // This caps the reward amount to the minimum of (reward, balance, dailyLimitRemaining) function _cappedReward(uint _reward) private view returns (uint) { uint _balance = address(this).balance; uint _remaining = getDailyLimitRemaining(); if (_reward > _balance) _reward = _balance; if (_reward > _remaining) _reward = _remaining; return _reward; } // IMPLEMENT BANKROLLABLE FUNCTIONS function getCollateral() public view returns (uint) {} function getWhitelistOwner() public view returns (address){ return getAdmin(); } }
Number of basis points to reward caller. 1 = .01%, 10 = .1%, 100 = 1%. Capped at .1%. Number of basis points to reward caller. 1 = .01%, 10 = .1%, 100 = 1%. Capped at 1%. How much to pay for games to start and end. These values are capped at 1 Ether. admin events base events task events Construct sets the registry and instantiates inherited classes.
{ uint constant public version = 1; uint public totalRewarded; uint public issueDividendRewardBips; uint public sendProfitsRewardBips; uint public monarchyStartReward; uint public monarchyEndReward; event Created(uint time); event DailyLimitChanged(uint time, address indexed owner, uint newValue); event IssueDividendRewardChanged(uint time, address indexed admin, uint newValue); event SendProfitsRewardChanged(uint time, address indexed admin, uint newValue); event MonarchyRewardsChanged(uint time, address indexed admin, uint startReward, uint endReward); event TaskError(uint time, address indexed caller, string msg); event RewardSuccess(uint time, address indexed caller, uint reward); event RewardFailure(uint time, address indexed caller, uint reward, string msg); event IssueDividendSuccess(uint time, address indexed treasury, uint profitsSent); event SendProfitsSuccess(uint time, address indexed bankrollable, uint profitsSent); event MonarchyGameStarted(uint time, address indexed addr, uint initialPrize); event MonarchyGamesRefreshed(uint time, uint numEnded, uint feesCollected); constructor(address _registry) public HasDailyLimit(1 ether) Bankrollable(_registry) UsingAdmin(_registry) UsingMonarchyController(_registry) { emit Created(now); } function setDailyLimit(uint _amount) public fromOwner { _setDailyLimit(_amount); emit DailyLimitChanged(now, msg.sender, _amount); } function setIssueDividendReward(uint _bips) public fromAdmin { require(_bips <= 10); issueDividendRewardBips = _bips; emit IssueDividendRewardChanged(now, msg.sender, _bips); } function setSendProfitsReward(uint _bips) public fromAdmin { require(_bips <= 100); sendProfitsRewardBips = _bips; emit SendProfitsRewardChanged(now, msg.sender, _bips); } function setMonarchyRewards(uint _startReward, uint _endReward) public fromAdmin { require(_startReward <= 1 ether); require(_endReward <= 1 ether); monarchyStartReward = _startReward; monarchyEndReward = _endReward; emit MonarchyRewardsChanged(now, msg.sender, _startReward, _endReward); } function doIssueDividend() public returns (uint _reward, uint _profits) { ITreasury _tr = getTreasury(); _profits = _tr.profitsSendable(); if (_profits == 0) { _taskError("No profits to send."); return; } if (_profits == 0) { _taskError("No profits were sent."); return; emit IssueDividendSuccess(now, address(_tr), _profits); } _sendReward(_reward); } function doIssueDividend() public returns (uint _reward, uint _profits) { ITreasury _tr = getTreasury(); _profits = _tr.profitsSendable(); if (_profits == 0) { _taskError("No profits to send."); return; } if (_profits == 0) { _taskError("No profits were sent."); return; emit IssueDividendSuccess(now, address(_tr), _profits); } _sendReward(_reward); } _profits = _tr.issueDividend(); function doIssueDividend() public returns (uint _reward, uint _profits) { ITreasury _tr = getTreasury(); _profits = _tr.profitsSendable(); if (_profits == 0) { _taskError("No profits to send."); return; } if (_profits == 0) { _taskError("No profits were sent."); return; emit IssueDividendSuccess(now, address(_tr), _profits); } _sendReward(_reward); } } else { _reward = (_profits * issueDividendRewardBips) / 10000; function issueDividendReward() public view returns (uint _reward, uint _profits) { _profits = getTreasury().profitsSendable(); _reward = _cappedReward((_profits * issueDividendRewardBips) / 10000); } function doSendProfits(address _bankrollable) public returns (uint _reward, uint _profits) { ITreasury _tr = getTreasury(); uint _oldTrBalance = address(_tr).balance; _IBankrollable(_bankrollable).sendProfits(); uint _newTrBalance = address(_tr).balance; if (_newTrBalance <= _oldTrBalance) { _taskError("No profits were sent."); return; _profits = _newTrBalance - _oldTrBalance; emit SendProfitsSuccess(now, _bankrollable, _profits); } _sendReward(_reward); } function doSendProfits(address _bankrollable) public returns (uint _reward, uint _profits) { ITreasury _tr = getTreasury(); uint _oldTrBalance = address(_tr).balance; _IBankrollable(_bankrollable).sendProfits(); uint _newTrBalance = address(_tr).balance; if (_newTrBalance <= _oldTrBalance) { _taskError("No profits were sent."); return; _profits = _newTrBalance - _oldTrBalance; emit SendProfitsSuccess(now, _bankrollable, _profits); } _sendReward(_reward); } } else { _reward = (_profits * sendProfitsRewardBips) / 10000; function sendProfitsReward(address _bankrollable) public view returns (uint _reward, uint _profits) { int _p = _IBankrollable(_bankrollable).profits(); if (_p <= 0) return; _profits = uint(_p); _reward = _cappedReward((_profits * sendProfitsRewardBips) / 10000); } function startMonarchyGame(uint _index) public { IMonarchyController _mc = getMonarchyController(); if (!_mc.getIsStartable(_index)){ _taskError("Game is not currently startable."); return; } if (_game == address(0)) { _taskError("MonarchyConroller.startDefinedGame() failed."); return; emit MonarchyGameStarted(now, _game, _mc.getInitialPrize(_index)); } } function startMonarchyGame(uint _index) public { IMonarchyController _mc = getMonarchyController(); if (!_mc.getIsStartable(_index)){ _taskError("Game is not currently startable."); return; } if (_game == address(0)) { _taskError("MonarchyConroller.startDefinedGame() failed."); return; emit MonarchyGameStarted(now, _game, _mc.getInitialPrize(_index)); } } address _game = _mc.startDefinedGame(_index); function startMonarchyGame(uint _index) public { IMonarchyController _mc = getMonarchyController(); if (!_mc.getIsStartable(_index)){ _taskError("Game is not currently startable."); return; } if (_game == address(0)) { _taskError("MonarchyConroller.startDefinedGame() failed."); return; emit MonarchyGameStarted(now, _game, _mc.getInitialPrize(_index)); } } } else { _sendReward(monarchyStartReward); function startMonarchyGameReward() public view returns (uint _reward, uint _index) { IMonarchyController _mc = getMonarchyController(); _index = _mc.getFirstStartableIndex(); if (_index > 0) _reward = _cappedReward(monarchyStartReward); } function refreshMonarchyGames() public { uint _numGamesEnded; uint _feesCollected; (_numGamesEnded, _feesCollected) = getMonarchyController().refreshGames(); emit MonarchyGamesRefreshed(now, _numGamesEnded, _feesCollected); if (_numGamesEnded == 0) { _taskError("No games ended."); _sendReward(_numGamesEnded * monarchyEndReward); } } function refreshMonarchyGames() public { uint _numGamesEnded; uint _feesCollected; (_numGamesEnded, _feesCollected) = getMonarchyController().refreshGames(); emit MonarchyGamesRefreshed(now, _numGamesEnded, _feesCollected); if (_numGamesEnded == 0) { _taskError("No games ended."); _sendReward(_numGamesEnded * monarchyEndReward); } } } else { function refreshMonarchyGamesReward() public view returns (uint _reward, uint _numEndable) { IMonarchyController _mc = getMonarchyController(); _numEndable = _mc.getNumEndableGames(); _reward = _cappedReward(_numEndable * monarchyEndReward); } function _taskError(string _msg) private { emit TaskError(now, msg.sender, _msg); } function _sendReward(uint _reward) private { uint _amount = _cappedReward(_reward); if (_reward > 0 && _amount == 0) { emit RewardFailure(now, msg.sender, _amount, "Not enough funds, or daily limit reached."); return; } if (msg.sender.call.value(_amount)()) { _useFromDailyLimit(_amount); totalRewarded += _amount; emit RewardSuccess(now, msg.sender, _amount); emit RewardFailure(now, msg.sender, _amount, "Reward rejected by recipient (out of gas, or revert)."); } } function _sendReward(uint _reward) private { uint _amount = _cappedReward(_reward); if (_reward > 0 && _amount == 0) { emit RewardFailure(now, msg.sender, _amount, "Not enough funds, or daily limit reached."); return; } if (msg.sender.call.value(_amount)()) { _useFromDailyLimit(_amount); totalRewarded += _amount; emit RewardSuccess(now, msg.sender, _amount); emit RewardFailure(now, msg.sender, _amount, "Reward rejected by recipient (out of gas, or revert)."); } } function _sendReward(uint _reward) private { uint _amount = _cappedReward(_reward); if (_reward > 0 && _amount == 0) { emit RewardFailure(now, msg.sender, _amount, "Not enough funds, or daily limit reached."); return; } if (msg.sender.call.value(_amount)()) { _useFromDailyLimit(_amount); totalRewarded += _amount; emit RewardSuccess(now, msg.sender, _amount); emit RewardFailure(now, msg.sender, _amount, "Reward rejected by recipient (out of gas, or revert)."); } } } else { function _cappedReward(uint _reward) private view returns (uint) { uint _balance = address(this).balance; uint _remaining = getDailyLimitRemaining(); if (_reward > _balance) _reward = _balance; if (_reward > _remaining) _reward = _remaining; return _reward; } function getCollateral() public view returns (uint) {} function getWhitelistOwner() public view returns (address){ return getAdmin(); } }
1,071,781
[ 1, 1854, 434, 10853, 3143, 358, 19890, 4894, 18, 404, 273, 263, 1611, 9, 16, 1728, 273, 263, 21, 9, 16, 2130, 273, 404, 9, 18, 11200, 1845, 622, 263, 21, 9, 18, 3588, 434, 10853, 3143, 358, 19890, 4894, 18, 404, 273, 263, 1611, 9, 16, 1728, 273, 263, 21, 9, 16, 2130, 273, 404, 9, 18, 11200, 1845, 622, 404, 9, 18, 9017, 9816, 358, 8843, 364, 28422, 358, 787, 471, 679, 18, 8646, 924, 854, 3523, 1845, 622, 404, 512, 1136, 18, 3981, 2641, 1026, 2641, 1562, 2641, 14291, 1678, 326, 4023, 471, 5934, 16020, 12078, 3318, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 2254, 5381, 1071, 1177, 273, 404, 31, 203, 565, 2254, 1071, 2078, 17631, 17212, 31, 203, 203, 565, 2254, 1071, 5672, 7244, 26746, 17631, 1060, 38, 7146, 31, 203, 565, 2254, 1071, 1366, 626, 18352, 17631, 1060, 38, 7146, 31, 203, 565, 2254, 1071, 6921, 991, 93, 1685, 17631, 1060, 31, 203, 565, 2254, 1071, 6921, 991, 93, 1638, 17631, 1060, 31, 203, 377, 203, 565, 871, 12953, 12, 11890, 813, 1769, 203, 565, 871, 463, 12857, 3039, 5033, 12, 11890, 813, 16, 1758, 8808, 3410, 16, 2254, 6129, 1769, 203, 565, 871, 11820, 7244, 26746, 17631, 1060, 5033, 12, 11890, 813, 16, 1758, 8808, 3981, 16, 2254, 6129, 1769, 203, 565, 871, 2479, 626, 18352, 17631, 1060, 5033, 12, 11890, 813, 16, 1758, 8808, 3981, 16, 2254, 6129, 1769, 203, 565, 871, 9041, 991, 93, 17631, 14727, 5033, 12, 11890, 813, 16, 1758, 8808, 3981, 16, 2254, 787, 17631, 1060, 16, 2254, 679, 17631, 1060, 1769, 203, 565, 871, 3837, 668, 12, 11890, 813, 16, 1758, 8808, 4894, 16, 533, 1234, 1769, 203, 565, 871, 534, 359, 1060, 4510, 12, 11890, 813, 16, 1758, 8808, 4894, 16, 2254, 19890, 1769, 203, 565, 871, 534, 359, 1060, 5247, 12, 11890, 813, 16, 1758, 8808, 4894, 16, 2254, 19890, 16, 533, 1234, 1769, 203, 565, 871, 11820, 7244, 26746, 4510, 12, 11890, 813, 16, 1758, 8808, 9787, 345, 22498, 16, 2254, 9214, 1282, 7828, 1769, 203, 565, 871, 2479, 626, 18352, 4510, 12, 11890, 813, 16, 1758, 8808, 11218, 30453, 16, 2254, 2 ]
./partial_match/1/0x4bA358F62c9f385E62D86812E2E914B82a5B5e8e/sources/PEPEPOPE.sol
set as marketing wallet
marketingWallet = address(0x7E9A1469c540d27F87F2Df9dFaC11494f735E908);
15,952,651
[ 1, 542, 487, 13667, 310, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 13667, 310, 16936, 273, 1758, 12, 20, 92, 27, 41, 29, 37, 3461, 8148, 71, 6564, 20, 72, 5324, 42, 11035, 42, 22, 40, 74, 29, 72, 29634, 39, 2499, 7616, 24, 74, 27, 4763, 41, 29, 6840, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <=0.9.0; pragma experimental ABIEncoderV2; import { IAaveV2LendingPoolAddressesProvider } from "./IAaveV2LendingPoolAddressesProvider.sol"; struct TokenData { string symbol; address tokenAddress; } struct ReserveConfigurationData { uint256 decimals; uint256 ltv; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; } struct ReserveDataProtocol { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; uint256 averageStableBorrowRate; uint256 liquidityIndex; uint256 variableBorrowIndex; uint40 lastUpdateTimestamp; } struct UserReserveData { uint256 currentATokenBalance; uint256 currentStableDebt; uint256 currentVariableDebt; uint256 principalStableDebt; uint256 scaledVariableDebt; uint256 stableBorrowRate; uint256 liquidityRate; uint40 stableRateLastUpdated; bool usageAsCollateralEnabled; } struct ReserveTokensAddresses { address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; } interface IAaveV2ProtocolDataProvider { // solhint-disable-next-line func-name-mixedcase function ADDRESSES_PROVIDER() external view returns (IAaveV2LendingPoolAddressesProvider); function getAllReservesTokens() external view returns (TokenData[] memory); function getAllATokens() external view returns (TokenData[] memory); function getReserveConfigurationData(address _asset) external view returns (ReserveConfigurationData memory); function getReserveData(address _asset) external view returns (ReserveDataProtocol memory); function getUserReserveData(address _asset, address _user) external view returns (UserReserveData memory); function getReserveTokensAddresses(address _asset) external view returns (ReserveTokensAddresses memory); }
solhint-disable-next-line func-name-mixedcase
interface IAaveV2ProtocolDataProvider { function ADDRESSES_PROVIDER() external view returns (IAaveV2LendingPoolAddressesProvider); function getAllReservesTokens() external view returns (TokenData[] memory); function getAllATokens() external view returns (TokenData[] memory); function getReserveConfigurationData(address _asset) external view returns (ReserveConfigurationData memory); function getReserveData(address _asset) external view returns (ReserveDataProtocol memory); function getUserReserveData(address _asset, address _user) external view returns (UserReserveData memory); function getReserveTokensAddresses(address _asset) external view returns (ReserveTokensAddresses memory); }
14,124,957
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1326, 17, 529, 17, 19562, 3593, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 37, 836, 58, 22, 5752, 20757, 288, 203, 565, 445, 11689, 7031, 1090, 55, 67, 26413, 1435, 3903, 1476, 1135, 261, 15188, 836, 58, 22, 48, 2846, 2864, 7148, 2249, 1769, 203, 203, 565, 445, 5514, 607, 264, 3324, 5157, 1435, 3903, 1476, 1135, 261, 1345, 751, 8526, 3778, 1769, 203, 203, 565, 445, 5514, 789, 3573, 1435, 3903, 1476, 1135, 261, 1345, 751, 8526, 3778, 1769, 203, 203, 565, 445, 31792, 6527, 1750, 751, 12, 2867, 389, 9406, 13, 3903, 1476, 1135, 261, 607, 6527, 1750, 751, 3778, 1769, 203, 203, 565, 445, 31792, 6527, 751, 12, 2867, 389, 9406, 13, 3903, 1476, 1135, 261, 607, 6527, 751, 5752, 3778, 1769, 203, 203, 565, 445, 4735, 607, 6527, 751, 12, 2867, 389, 9406, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 1299, 607, 6527, 751, 3778, 1769, 203, 203, 565, 445, 31792, 6527, 5157, 7148, 12, 2867, 389, 9406, 13, 3903, 1476, 1135, 261, 607, 6527, 5157, 7148, 3778, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x9E94010A00dE5fb332B66372B29e69B09fa8373e/sources/HashGame.sol
console.logBytes1(getCharAt("123456789", 8));
function playGame() public { require(hasValidInsurance(), "User does not have valid insurance"); require(!hasPlayedMaxGameRound(), "User has played maximum rounds of game"); uint256 playedRound = userToGameMap[msg.sender].length; uint256 lastStakedValue = 0; if (playedRound > 0 && userToGameMap[msg.sender][playedRound - 1].hasPlayed == false) { GameRound memory lastCreatedRound = userToGameMap[msg.sender][playedRound - 1]; emit NewGameRound( lastCreatedRound.round, lastCreatedRound.hasPlayed, lastCreatedRound.isWon, lastCreatedRound.stakeValue ); return; } if (playedRound > 0) { lastStakedValue = userToGameMap[msg.sender][playedRound - 1].stakeValue; } uint256 currentStakeValue = lastStakedValue > 0 ? lastStakedValue * nextGameMultiplier : 1; GameRound memory newRound = GameRound(playedRound + 1, false, false, currentStakeValue); userToGameMap[msg.sender].push(newRound); emit NewGameRound(newRound.round, newRound.hasPlayed, newRound.isWon, newRound.stakeValue); }
1,866,910
[ 1, 8698, 18, 1330, 2160, 21, 12, 588, 2156, 861, 2932, 28462, 20277, 3113, 1725, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6599, 12496, 1435, 1071, 288, 203, 3639, 2583, 12, 5332, 1556, 5048, 295, 1359, 9334, 315, 1299, 1552, 486, 1240, 923, 2763, 295, 1359, 8863, 203, 3639, 2583, 12, 5, 5332, 11765, 329, 2747, 12496, 11066, 9334, 315, 1299, 711, 6599, 329, 4207, 21196, 434, 7920, 8863, 203, 203, 203, 3639, 2254, 5034, 6599, 329, 11066, 273, 729, 774, 12496, 863, 63, 3576, 18, 15330, 8009, 2469, 31, 203, 3639, 2254, 5034, 1142, 510, 9477, 620, 273, 374, 31, 203, 203, 3639, 309, 261, 1601, 329, 11066, 405, 374, 597, 729, 774, 12496, 863, 63, 3576, 18, 15330, 6362, 1601, 329, 11066, 300, 404, 8009, 5332, 11765, 329, 422, 629, 13, 288, 203, 5411, 14121, 11066, 3778, 1142, 6119, 11066, 273, 729, 774, 12496, 863, 63, 3576, 18, 15330, 6362, 1601, 329, 11066, 300, 404, 15533, 203, 5411, 3626, 1166, 12496, 11066, 12, 203, 7734, 1142, 6119, 11066, 18, 2260, 16, 203, 7734, 1142, 6119, 11066, 18, 5332, 11765, 329, 16, 203, 7734, 1142, 6119, 11066, 18, 291, 59, 265, 16, 203, 7734, 1142, 6119, 11066, 18, 334, 911, 620, 203, 5411, 11272, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1601, 329, 11066, 405, 374, 13, 288, 203, 5411, 1142, 510, 9477, 620, 273, 729, 774, 12496, 863, 63, 3576, 18, 15330, 6362, 1601, 329, 11066, 300, 404, 8009, 334, 911, 620, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 783, 510, 911, 620, 273, 1142, 510, 9477, 620, 405, 374, 692, 1142, 510, 9477, 620, 2 ]
./full_match/5/0x88E6A8bA858c86D4c395ed44797fA6Abf3a99fa7/sources/src/lib/SlotsDataTypes.sol
Amount of Quote Token related to the sale of options Up & Down.
uint256 totalQuoteTokenInContest;
11,622,902
[ 1, 6275, 434, 21695, 3155, 3746, 358, 326, 272, 5349, 434, 702, 1948, 473, 10077, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 2078, 10257, 1345, 382, 660, 395, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import "../tokens/IERC20.sol"; import "../tokens/IERC721Enumerable.sol"; import "../utils/Ownable.sol"; import "../utils/ReentrancyGuard.sol"; interface Minter { function mint(address to, uint256 tokenId) external; } contract WaveLockSaleWithMint is Ownable, ReentrancyGuard { address public nft; uint256 constant BASE = 10**18; uint256 public price; uint256 public amountForSale; uint256 public amountSold; uint256 public startBlock; uint256 public wave = 0; uint256 public waveBlockLength = 20; mapping(uint256 => mapping(address => bool)) blockLock; mapping(address => uint256) balance; constructor(address _nft, uint256 _startBlock) Ownable() ReentrancyGuard() { nft = _nft; startBlock = _startBlock; } function loadSale(uint256 count) external { require(msg.sender == nft); amountForSale = count; } function buy(uint256 count) external payable nonReentrant { require(block.number > startBlock, "Sale has not started"); require(count > 0, "Cannot mint 0"); require(amountSold < amountForSale, "Sold out! Sorry!"); refreshWave(); require(!blockLock[wave][msg.sender], "Locked for this wave"); require(count < maxPerTX(wave), "Cap"); // Adjust for the last mint being incomplete. uint256 ethAmountOwed; if (amountSold + count > amountForSale) { uint256 amountRemaining = amountForSale-amountSold; ethAmountOwed = price * (count-amountRemaining); count = amountRemaining; } // Update the amount the person is eligible for minting. amountSold += count; balance[msg.sender] += count; // Lock this address for the phase. blockLock[wave][msg.sender] = true; if (ethAmountOwed > 0) { (bool success, ) = msg.sender.call{ value: ethAmountOwed }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } function mint(uint256 count) external { require(count > 0); require(count <= balance[msg.sender]); balance[msg.sender] -= count; // Mint to the owner. uint256 currentSupply = IERC721Enumerable(nft).totalSupply(); for (uint256 i = 0; i < count; i++) { Minter(nft).mint(msg.sender, currentSupply + i); } } function refreshWave() internal { uint256 blocksSinceStart = block.number - startBlock; uint256 newWave = blocksSinceStart/waveBlockLength; if (newWave != wave) { wave = newWave; } } function maxPerTX(uint256 _wave) internal pure returns (uint256) { if (_wave == 0) { return 2; } else if (_wave == 1) { return 8; } else if (_wave == 2) { return 20; } else { return 50; } } }
Lock this address for the phase.
blockLock[wave][msg.sender] = true;
13,079,500
[ 1, 2531, 333, 1758, 364, 326, 6855, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1203, 2531, 63, 17838, 6362, 3576, 18, 15330, 65, 273, 638, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0x8101F97D399e110067Ff785b783d61545B5f18D2/sources/contracts/Quote.sol
@dev Lock implementation contract by default. Can be overridden for test harnesses.
function _lockImplementation() internal pure virtual returns (bool) { return true; }
16,766,242
[ 1, 2531, 4471, 6835, 635, 805, 18, 4480, 506, 11000, 364, 1842, 366, 1303, 403, 281, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 739, 13621, 1435, 2713, 16618, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xEda7Ca698cF02E5b95F814266b7db1665E54Bc13/sources/browser/ss.sol
Amount that is paid for staking 1 second
uint public rewardAmount;
9,674,079
[ 1, 6275, 716, 353, 30591, 364, 384, 6159, 404, 2205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 1071, 19890, 6275, 31, 12900, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x0Ac7ac8C6Eb5BbBEbE2d02E6B6f5B2B8e05759f1/sources/contracts/LP.sol
* @notice Indicate the game `gameId` as canceled. @param gameId the game ID/
function cancelGame(uint256 gameId) external restricted(this.cancelGame.selector) { Game storage game = _getGame(gameId); if (game.canceled) revert GameAlreadyCanceled(); lockedLiquidity -= game.lockedLiquidity; game.canceled = true; emit GameCanceled(gameId); }
14,285,406
[ 1, 3866, 2659, 326, 7920, 1375, 13957, 548, 68, 487, 17271, 18, 282, 7920, 548, 326, 7920, 1599, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3755, 12496, 12, 11890, 5034, 7920, 548, 13, 203, 3639, 3903, 203, 3639, 15693, 12, 2211, 18, 10996, 12496, 18, 9663, 13, 203, 565, 288, 203, 3639, 14121, 2502, 7920, 273, 389, 588, 12496, 12, 13957, 548, 1769, 203, 3639, 309, 261, 13957, 18, 10996, 329, 13, 15226, 14121, 9430, 23163, 5621, 203, 203, 3639, 8586, 48, 18988, 24237, 3947, 7920, 18, 15091, 48, 18988, 24237, 31, 203, 3639, 7920, 18, 10996, 329, 273, 638, 31, 203, 3639, 3626, 14121, 23163, 12, 13957, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; /** * @title Token * @dev BEP20 compatible token. */ contract Token is ERC20Burnable, Ownable { /** * @dev Mints all tokens to deployer * @param amount_ Initial supply * @param name_ Token name. * @param symbol_ Token symbol. */ constructor( uint256 amount_, string memory name_, string memory symbol_ ) ERC20(name_, symbol_) { _mint(_msgSender(), amount_); } /** * @dev Returns the address of the current owner. * * IMPORTANT: This method is required to be able to transfer tokens directly between their Binance Chain * and Binance Smart Chain. More on this issue can be found in: * https://github.com/binance-chain/BEPs/blob/master/BEP20.md#5116-getowner */ function getOwner() external view returns (address) { return owner(); } function decimals() public pure override returns (uint8) { return 4; } }
* @title Token @dev BEP20 compatible token./
contract Token is ERC20Burnable, Ownable { constructor( uint256 amount_, string memory name_, string memory symbol_ pragma solidity 0.8.10; ) ERC20(name_, symbol_) { _mint(_msgSender(), amount_); } function getOwner() external view returns (address) { return owner(); } function decimals() public pure override returns (uint8) { return 4; } }
14,124,464
[ 1, 1345, 225, 9722, 52, 3462, 7318, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 353, 4232, 39, 3462, 38, 321, 429, 16, 14223, 6914, 288, 203, 225, 3885, 12, 203, 565, 2254, 5034, 3844, 67, 16, 203, 565, 533, 3778, 508, 67, 16, 203, 565, 533, 3778, 3273, 67, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 2163, 31, 203, 225, 262, 4232, 39, 3462, 12, 529, 67, 16, 3273, 67, 13, 288, 203, 565, 389, 81, 474, 24899, 3576, 12021, 9334, 3844, 67, 1769, 203, 225, 289, 203, 203, 225, 445, 13782, 1435, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 3410, 5621, 203, 225, 289, 203, 203, 225, 445, 15105, 1435, 1071, 16618, 3849, 1135, 261, 11890, 28, 13, 288, 203, 565, 327, 1059, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title MultiOwnable * @dev The MultiOwnable contract has owners addresses and provides basic authorization control * functions, this simplifies the implementation of "users permissions". */ contract MultiOwnable { address public manager; // address used to set owners address[] public owners; mapping(address => bool) public ownerByAddress; event AddOwner(address owner); event RemoveOwner(address owner); modifier onlyOwner() { require(ownerByAddress[msg.sender] == true); _; } /** * @dev MultiOwnable constructor sets the manager */ function MultiOwnable() public { manager = msg.sender; _addOwner(msg.sender); } /** * @dev Function to add owner address */ function addOwner(address _owner) public { require(msg.sender == manager); _addOwner(_owner); } /** * @dev Function to remove owner address */ function removeOwner(address _owner) public { require(msg.sender == manager); _removeOwner(_owner); } function _addOwner(address _owner) internal { ownerByAddress[_owner] = true; owners.push(_owner); AddOwner(_owner); } function _removeOwner(address _owner) internal { if (owners.length == 0) return; ownerByAddress[_owner] = false; uint id = indexOf(_owner); remove(id); RemoveOwner(_owner); } function getOwners() public constant returns (address[]) { return owners; } function indexOf(address value) internal returns(uint) { uint i = 0; while (i < owners.length) { if (owners[i] == value) { break; } i++; } return i; } function remove(uint index) internal { if (index >= owners.length) return; for (uint i = index; i<owners.length-1; i++){ owners[i] = owners[i+1]; } delete owners[owners.length-1]; owners.length--; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title IERC20Token - ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20Token { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; 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 PricingStrategy { using SafeMath for uint256; uint256 public constant FIRST_ROUND = 1523664001; //2018.04.14 00:00:01 GMT uint256 public constant FIRST_ROUND_RATE = 20; // FIRST ROUND BONUS RATE 20% uint256 public constant SECOND_ROUND = 1524268801; //2018.04.21 00:00:01 GMT uint256 public constant SECOND_ROUND_RATE = 10; // SECOND ROUND BONUS RATE 10% uint256 public constant FINAL_ROUND_RATE = 0; //FINAL ROUND BONUS RATE 0% function PricingStrategy() public { } function getRate() public constant returns(uint256 rate) { if (now<FIRST_ROUND) { return (FIRST_ROUND_RATE); } else if (now<SECOND_ROUND) { return (SECOND_ROUND_RATE); } else { return (FINAL_ROUND_RATE); } } } contract CrowdSale is MultiOwnable { using SafeMath for uint256; enum ICOState { NotStarted, Started, Stopped, Finished } // ICO SALE STATES struct Stats { uint256 TotalContrAmount; ICOState State; uint256 TotalContrCount; } event Contribution(address contraddress, uint256 ethamount, uint256 tokenamount); event PresaleTransferred(address contraddress, uint256 tokenamount); event TokenOPSPlatformTransferred(address contraddress, uint256 tokenamount); event OVISBookedTokensTransferred(address contraddress, uint256 tokenamount); event OVISSaleBooked(uint256 jointToken); event OVISReservedTokenChanged(uint256 jointToken); event RewardPoolTransferred(address rewardpooladdress, uint256 tokenamount); event OPSPoolTransferred(address OPSpooladdress, uint256 tokenamount); event SaleStarted(); event SaleStopped(); event SaleContinued(); event SoldOutandSaleStopped(); event SaleFinished(); event TokenAddressChanged(address jointaddress, address OPSAddress); event StrategyAddressChanged(address strategyaddress); event Funded(address fundaddress, uint256 amount); uint256 public constant MIN_ETHER_CONTR = 0.1 ether; // MINIMUM ETHER CONTRIBUTION uint256 public constant MAX_ETHER_CONTR = 100 ether; // MAXIMUM ETHER CONTRIBUTION uint256 public constant DECIMALCOUNT = 10**18; uint256 public constant JOINT_PER_ETH = 8000; // 1 ETH = 8000 JOINT uint256 public constant PRESALE_JOINTTOKENS = 5000000; // PRESALE 500 ETH * 10000 JOINT AMOUNT uint256 public constant TOKENOPSPLATFORM_JOINTTOKENS = 25000000; // TOKENOPS PLAFTORM RESERVED AMOUNT uint256 public constant MAX_AVAILABLE_JOINTTOKENS = 100000000; // PRESALE JOINT TOKEN SALE AMOUNT uint256 public AVAILABLE_JOINTTOKENS = uint256(100000000).mul(DECIMALCOUNT); uint256 public OVISRESERVED_TOKENS = 25000000; // RESERVED TOKEN AMOUNT FOR OVIS PARTNER SALE uint256 public OVISBOOKED_TOKENS = 0; uint256 public OVISBOOKED_BONUSTOKENS = 0; uint256 public constant SALE_START_TIME = 1523059201; //UTC 2018-04-07 00:00:01 uint256 public ICOSALE_JOINTTOKENS = 0; // ICO CONTRACT TOTAL JOINT SALE AMOUNT uint256 public ICOSALE_BONUSJOINTTOKENS = 0; // ICO CONTRACT TOTAL JOINT BONUS AMOUNT uint256 public TOTAL_CONTRIBUTOR_COUNT = 0; // ICO SALE TOTAL CONTRIBUTOR COUNT ICOState public CurrentState; // ICO SALE STATE IERC20Token public JointToken; IERC20Token public OPSToken; PricingStrategy public PriceStrategy; address public FundAddress = 0x25Bc52CBFeB86f6f12EaddF77560b02c4617DC21; address public RewardPoolAddress = 0xEb1FAef9068b6B8f46b50245eE877dA5b03D98C9; address public OvisAddress = 0x096A5166F75B5B923234841F69374de2F47F9478; address public PresaleAddress = 0x3e5EF0eC822B519eb0a41f94b34e90D16ce967E8; address public TokenOPSSaleAddress = 0x8686e49E07Bde4F389B0a5728fCe8713DB83602b; address public StrategyAddress = 0xe2355faB9239d5ddaA071BDE726ceb2Db876B8E2; address public OPSPoolAddress = 0xEA5C0F39e5E3c742fF6e387394e0337e7366a121; modifier checkCap() { require(msg.value>=MIN_ETHER_CONTR); require(msg.value<=MAX_ETHER_CONTR); _; } modifier checkBalance() { require(JointToken.balanceOf(address(this))>0); require(OPSToken.balanceOf(address(this))>0); _; } modifier checkTime() { require(now>=SALE_START_TIME); _; } modifier checkState() { require(CurrentState == ICOState.Started); _; } function CrowdSale() { PriceStrategy = PricingStrategy(StrategyAddress); CurrentState = ICOState.NotStarted; uint256 _soldtokens = PRESALE_JOINTTOKENS.add(TOKENOPSPLATFORM_JOINTTOKENS).add(OVISRESERVED_TOKENS); _soldtokens = _soldtokens.mul(DECIMALCOUNT); AVAILABLE_JOINTTOKENS = AVAILABLE_JOINTTOKENS.sub(_soldtokens); } function() payable public checkState checkTime checkBalance checkCap { contribute(); } /** * @dev calculates token amounts and sends to contributor */ function contribute() private { uint256 _jointAmount = 0; uint256 _jointBonusAmount = 0; uint256 _jointTransferAmount = 0; uint256 _bonusRate = 0; uint256 _ethAmount = msg.value; if (msg.value.mul(JOINT_PER_ETH)>AVAILABLE_JOINTTOKENS) { _ethAmount = AVAILABLE_JOINTTOKENS.div(JOINT_PER_ETH); } else { _ethAmount = msg.value; } _bonusRate = PriceStrategy.getRate(); _jointAmount = (_ethAmount.mul(JOINT_PER_ETH)); _jointBonusAmount = _ethAmount.mul(JOINT_PER_ETH).mul(_bonusRate).div(100); _jointTransferAmount = _jointAmount.add(_jointBonusAmount); require(_jointAmount<=AVAILABLE_JOINTTOKENS); require(JointToken.transfer(msg.sender, _jointTransferAmount)); require(OPSToken.transfer(msg.sender, _jointTransferAmount)); if (msg.value>_ethAmount) { msg.sender.transfer(msg.value.sub(_ethAmount)); CurrentState = ICOState.Stopped; SoldOutandSaleStopped(); } AVAILABLE_JOINTTOKENS = AVAILABLE_JOINTTOKENS.sub(_jointAmount); ICOSALE_JOINTTOKENS = ICOSALE_JOINTTOKENS.add(_jointAmount); ICOSALE_BONUSJOINTTOKENS = ICOSALE_BONUSJOINTTOKENS.add(_jointBonusAmount); TOTAL_CONTRIBUTOR_COUNT = TOTAL_CONTRIBUTOR_COUNT.add(1); Contribution(msg.sender, _ethAmount, _jointTransferAmount); } /** * @dev book OVIS partner sale tokens */ function bookOVISSale(uint256 _rate, uint256 _jointToken) onlyOwner public { OVISBOOKED_TOKENS = OVISBOOKED_TOKENS.add(_jointToken); require(OVISBOOKED_TOKENS<=OVISRESERVED_TOKENS.mul(DECIMALCOUNT)); uint256 _bonus = _jointToken.mul(_rate).div(100); OVISBOOKED_BONUSTOKENS = OVISBOOKED_BONUSTOKENS.add(_bonus); OVISSaleBooked(_jointToken); } /** * @dev changes OVIS partner sale reserved tokens */ function changeOVISReservedToken(uint256 _jointToken) onlyOwner public { if (_jointToken > OVISRESERVED_TOKENS) { AVAILABLE_JOINTTOKENS = AVAILABLE_JOINTTOKENS.sub((_jointToken.sub(OVISRESERVED_TOKENS)).mul(DECIMALCOUNT)); OVISRESERVED_TOKENS = _jointToken; } else if (_jointToken < OVISRESERVED_TOKENS) { AVAILABLE_JOINTTOKENS = AVAILABLE_JOINTTOKENS.add((OVISRESERVED_TOKENS.sub(_jointToken)).mul(DECIMALCOUNT)); OVISRESERVED_TOKENS = _jointToken; } OVISReservedTokenChanged(_jointToken); } /** * @dev changes Joint Token and OPS Token contract address */ function changeTokenAddress(address _jointAddress, address _OPSAddress) onlyOwner public { JointToken = IERC20Token(_jointAddress); OPSToken = IERC20Token(_OPSAddress); TokenAddressChanged(_jointAddress, _OPSAddress); } /** * @dev changes Pricing Strategy contract address, which calculates token amounts to give */ function changeStrategyAddress(address _strategyAddress) onlyOwner public { PriceStrategy = PricingStrategy(_strategyAddress); StrategyAddressChanged(_strategyAddress); } /** * @dev transfers presale token amounts to contributors */ function transferPresaleTokens() private { require(JointToken.transfer(PresaleAddress, PRESALE_JOINTTOKENS.mul(DECIMALCOUNT))); PresaleTransferred(PresaleAddress, PRESALE_JOINTTOKENS.mul(DECIMALCOUNT)); } /** * @dev transfers presale token amounts to contributors */ function transferTokenOPSPlatformTokens() private { require(JointToken.transfer(TokenOPSSaleAddress, TOKENOPSPLATFORM_JOINTTOKENS.mul(DECIMALCOUNT))); TokenOPSPlatformTransferred(TokenOPSSaleAddress, TOKENOPSPLATFORM_JOINTTOKENS.mul(DECIMALCOUNT)); } /** * @dev transfers token amounts to other ICO platforms */ function transferOVISBookedTokens() private { uint256 _totalTokens = OVISBOOKED_TOKENS.add(OVISBOOKED_BONUSTOKENS); if(_totalTokens>0) { require(JointToken.transfer(OvisAddress, _totalTokens)); require(OPSToken.transfer(OvisAddress, _totalTokens)); } OVISBookedTokensTransferred(OvisAddress, _totalTokens); } /** * @dev transfers remaining unsold token amount to reward pool */ function transferRewardPool() private { uint256 balance = JointToken.balanceOf(address(this)); if(balance>0) { require(JointToken.transfer(RewardPoolAddress, balance)); } RewardPoolTransferred(RewardPoolAddress, balance); } /** * @dev transfers remaining OPS token amount to pool */ function transferOPSPool() private { uint256 balance = OPSToken.balanceOf(address(this)); if(balance>0) { require(OPSToken.transfer(OPSPoolAddress, balance)); } OPSPoolTransferred(OPSPoolAddress, balance); } /** * @dev start function to start crowdsale for contribution */ function startSale() onlyOwner public { require(CurrentState == ICOState.NotStarted); require(JointToken.balanceOf(address(this))>0); require(OPSToken.balanceOf(address(this))>0); CurrentState = ICOState.Started; transferPresaleTokens(); transferTokenOPSPlatformTokens(); SaleStarted(); } /** * @dev stop function to stop crowdsale for contribution */ function stopSale() onlyOwner public { require(CurrentState == ICOState.Started); CurrentState = ICOState.Stopped; SaleStopped(); } /** * @dev continue function to continue crowdsale for contribution */ function continueSale() onlyOwner public { require(CurrentState == ICOState.Stopped); CurrentState = ICOState.Started; SaleContinued(); } /** * @dev finish function to finish crowdsale for contribution */ function finishSale() onlyOwner public { if (this.balance>0) { FundAddress.transfer(this.balance); } transferOVISBookedTokens(); transferRewardPool(); transferOPSPool(); CurrentState = ICOState.Finished; SaleFinished(); } /** * @dev funds contract's balance to fund address */ function getFund(uint256 _amount) onlyOwner public { require(_amount<=this.balance); FundAddress.transfer(_amount); Funded(FundAddress, _amount); } function getStats() public constant returns(uint256 TotalContrAmount, ICOState State, uint256 TotalContrCount) { uint256 totaltoken = 0; totaltoken = ICOSALE_JOINTTOKENS.add(PRESALE_JOINTTOKENS.mul(DECIMALCOUNT)); totaltoken = totaltoken.add(TOKENOPSPLATFORM_JOINTTOKENS.mul(DECIMALCOUNT)); totaltoken = totaltoken.add(OVISBOOKED_TOKENS); return (totaltoken, CurrentState, TOTAL_CONTRIBUTOR_COUNT); } function destruct() onlyOwner public { require(CurrentState == ICOState.Finished); selfdestruct(FundAddress); } }
TOKENOPS PLAFTORM RESERVED AMOUNT
uint256 public constant TOKENOPSPLATFORM_JOINTTOKENS = 25000000;
6,477,457
[ 1, 8412, 3665, 55, 25564, 4464, 3466, 2438, 19501, 432, 5980, 5321, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 14275, 3665, 3118, 12190, 4983, 67, 18800, 23187, 55, 273, 6969, 9449, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "../../open-zeppelin/contracts/math/SafeMath.sol"; import "./OwnerStandardERC20.sol"; import "./ERC20Exchangable.sol"; import "./OperationHolder.sol"; /** * @title Basic treasury smart contract * @author Biglabs Pte. Ltd. * @dev : Treasury smart contract - use for Buy/Sell tokens */ contract BasicTreasury is OperationHolder, ERC20Exchangable { using SafeMath for uint; address internal feeCollector; //How to calculate fee: true if fixed, else is percentage bool internal fixedFee; //Fee (% if fixedFee=false, else number of tokens) uint internal fee; uint public constant MAX_PERCENTAGE_FEE = 50; /** * @dev Basic Treasury constructor * @param _operation Address of operation smart contract */ constructor(Operationable _operation) public OperationHolder(_operation) { require(operation.getERC20().owner() == msg.sender); } /** * @dev Set fee collector * @param _feeCollector wallet for collect fee */ function setFeeCollector(address _feeCollector) public onlyOwner{ feeCollector = _feeCollector; } /** * @dev Get fee collector */ function getFeeCollector() public view returns(address) { return feeCollector; } /** * @dev Set fee * @param _fee Fee (% if _fixedFee=false, else number of tokens) */ function setFee(uint _fee) public onlyOwner { if(!fixedFee) { require(_fee < MAX_PERCENTAGE_FEE); } fee = _fee; } /** * @dev Get fee * @return % if _fixedFee=false, else number of tokens */ function getFee() public view returns(uint) { return fee; } /** * @dev Check whether this is fixed fee */ function isFixedFee() public view returns(bool){ return fixedFee; } /** * @dev Set fee model * @param _fixedFee How to calculate fee: true if fixed, else is percentage * @param _fee Fee (% if _fixedFee=false, else number of tokens) */ function setFeeModel(bool _fixedFee, uint _fee) public onlyOwner { if(!_fixedFee) { require(_fee < MAX_PERCENTAGE_FEE); } fixedFee = _fixedFee; fee = _fee; } /** * @notice This method called by ERC20 smart contract * @dev Buy ERC20 tokens in other blockchain * @param _from Bought address * @param _to The address in other blockchain to transfer tokens to. * @param _value Number of tokens */ function autoBuyERC20(address _from, address _to, uint _value) public onlyERC20 { emit Buy(_from, _to, _value); } /** * @dev called by Bridge when a bought event occurs, it will transfer ERC20 tokens to receiver address * @param _hash Transaction hash in other blockchain * @param _from bought address * @param _to The received address * @param _value Number of tokens */ function sold(bytes32 _hash, address _from, address _to, uint _value) public onlyOperation returns(bool) { if (operation.getERC20().transfer(_to, _value)) { emit Sold(msg.sender, _hash, _from, _to, _value, 0); return true; } return false; } /** * @dev get minimum tokens can be sold */ function minimumTokens() public view returns(uint) { return calculateMinimumTokens(fixedFee, fee); } /** * @dev calculate minimum tokens can be sold * @param _fixedFee How to calculate fee: true if fixed, else is percentage * @param _fee Fee (% if _fixedFee=false, else number of tokens) */ function calculateMinimumTokens(bool _fixedFee, uint _fee) public pure returns(uint) { if(_fixedFee) { return _fee; } if(_fee == 0) { return 0; } uint ret = uint(100).div(_fee); if( _fee.mul(ret) < 100) { return ret.add(1); } return ret; } /** * @dev called by Bridge when a bought event occurs, it will transfer ERC20 tokens to receiver address * @param _hash Transaction hash in other blockchain * @param _from bought address * @param _to The received address * @param _value Number of tokens */ function soldWithFee(bytes32 _hash, address _from, address _to, uint _value) public onlyOperation returns(bool) { require(_value >= minimumTokens()); uint f = calculateFee(fixedFee, fee, _value); uint noTokens = _value - f; operation.getERC20().transfer(feeCollector, f); if (operation.getERC20().transfer(_to, noTokens)) { emit Sold(msg.sender, _hash, _from, _to, noTokens, f); return true; } return false; } /** * @dev Calculate fee * @param _fixedFee How to calculate fee: true if fixed, else is percentage * @param _fee Fee (% if _fixedFee=false, else number of tokens) * @param _value number of tokens */ function calculateFee(bool _fixedFee, uint _fee, uint _value) public pure returns(uint) { if(_fixedFee) { return _fee; } if(_fee == 0) { return 0; } return _value.mul(_fee).div(100); } /** * @dev Get number of Mozo ERC20 tokens in this smart contract */ function noTokens() public view returns(uint) { return operation.getERC20().totalSupply(); } /** * @dev Withdraw all tokens in case swapping contracts */ function _withdraw() private { operation.getERC20().transfer(getOwner(), noTokens()); } /** * @dev Terminates the contract. */ function destroy() public onlyOwner { _withdraw(); selfdestruct(getOwner()); } }
* @dev Get number of Mozo ERC20 tokens in this smart contract/
function noTokens() public view returns(uint) { return operation.getERC20().totalSupply(); }
13,089,346
[ 1, 967, 1300, 434, 19058, 83, 4232, 39, 3462, 2430, 316, 333, 13706, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1158, 5157, 1435, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 202, 202, 2463, 1674, 18, 588, 654, 39, 3462, 7675, 4963, 3088, 1283, 5621, 203, 202, 97, 203, 202, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) 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 StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } //name this contract whatever you'd like contract HotpotSwap is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function HotpotSwap( ) { balances[msg.sender] = 18000000000000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 18000000000000000000000; // Update total supply (100000 for example) name = "Hotpot Swap"; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = "HOTS"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //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(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
Update total supply (100000 for example)
totalSupply = 18000000000000000000000;
10,050,145
[ 1, 1891, 2078, 14467, 261, 21, 11706, 364, 3454, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 3088, 1283, 273, 6549, 12648, 12648, 11706, 31, 7682, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xcC48E741996B0d77b38d9dC2bf9217e65E368E06/sources/Mailbox.sol
* @notice Returns the validator ECDSA signature at `_index`. @dev Assumes signatures are sorted by validator @dev Assumes `_metadata` encodes `threshold` signatures. @dev Assumes `_index` is less than `threshold` @param _metadata ABI encoded Multisig ISM metadata. @param _index The index of the signature to return. @return The validator ECDSA signature at `_index`./
function signatureAt(bytes calldata _metadata, uint256 _index) internal pure returns (bytes calldata) { uint256 _start = SIGNATURES_OFFSET + (_index * SIGNATURE_LENGTH); uint256 _end = _start + SIGNATURE_LENGTH; return _metadata[_start:_end]; }
4,297,999
[ 1, 1356, 326, 4213, 7773, 19748, 3372, 622, 1375, 67, 1615, 8338, 225, 25374, 14862, 854, 3115, 635, 4213, 225, 25374, 1375, 67, 4165, 68, 16834, 1375, 8699, 68, 14862, 18, 225, 25374, 1375, 67, 1615, 68, 353, 5242, 2353, 1375, 8699, 68, 225, 389, 4165, 10336, 45, 3749, 7778, 291, 360, 4437, 49, 1982, 18, 225, 389, 1615, 1021, 770, 434, 326, 3372, 358, 327, 18, 327, 1021, 4213, 7773, 19748, 3372, 622, 1375, 67, 1615, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3372, 861, 12, 3890, 745, 892, 389, 4165, 16, 2254, 5034, 389, 1615, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 745, 892, 13, 203, 565, 288, 203, 3639, 2254, 5034, 389, 1937, 273, 12057, 10511, 55, 67, 11271, 397, 261, 67, 1615, 380, 12057, 10511, 67, 7096, 1769, 203, 3639, 2254, 5034, 389, 409, 273, 389, 1937, 397, 12057, 10511, 67, 7096, 31, 203, 3639, 327, 389, 4165, 63, 67, 1937, 30, 67, 409, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0xeE969ACAfe781291cEF3DE8FadB212d4Ea93EbF1/sources/browser/tests/core/NBUNIERC20.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 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 NBUNIERC20 is Context, INBUNIERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; event LiquidityAddition(address indexed dst, uint value); event LPTokenClaimed(address dst, uint value); uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 public contractStartTimestamp; function name() public view returns (string memory) { return _name; } function initialSetup(address router, address factory) internal { _name = "wuzhong"; _symbol = "zhuanqianlo"; _decimals = 18; _mint(address(this), initialSupply); contractStartTimestamp = block.timestamp; createUniswapPairMainnet(); } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public override view returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public override view returns (uint256) { return _balances[_owner]; } IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Factory public uniswapFactory; address public tokenUniswapPair; function createUniswapPairMainnet() public returns (address) { require(tokenUniswapPair == address(0), "Token: pool already created"); tokenUniswapPair = uniswapFactory.createPair( address(uniswapRouterV2.WETH()), address(this) ); return tokenUniswapPair; } string public liquidityGenerationParticipationAgreement = "I'm not a resident of the United States \n I understand that this contract is provided with no warranty of any kind. \n I agree to not hold the contract creators, CORE team members or anyone associated with this event liable for any damage monetary and otherwise I might onccur. \n I understand that any smart contract interaction carries an inherent risk."; function getSecondsLeftInLiquidityGenerationEvent() public view returns (uint256) { require(liquidityGenerationOngoing(), "Event over"); console.log("7 minutes since start is", contractStartTimestamp.add(7 minutes), "Time now is", block.timestamp); return contractStartTimestamp.add(7 minutes).sub(block.timestamp); } function liquidityGenerationOngoingbk() public view returns (bool) { console.log("7 days since start is", contractStartTimestamp.add(7 days), "Time now is", block.timestamp); console.log("liquidity generation ongoing", contractStartTimestamp.add(7 days) < block.timestamp); return contractStartTimestamp.add(7 days) > block.timestamp; } function liquidityGenerationOngoing() public view returns (bool) { console.log("7 minutes since start is", contractStartTimestamp.add(7 minutes), "Time now is", block.timestamp); console.log("liquidity generation ongoing", contractStartTimestamp.add(7 minutes) < block.timestamp); return contractStartTimestamp.add(7 minutes) > block.timestamp; } function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner { (bool success, ) = msg.sender.call.value(address(this).balance)(""); require(success, "Transfer failed."); _balances[msg.sender] = _balances[address(this)]; _balances[address(this)] = 0; } uint256 public totalLPTokensMinted; uint256 public totalETHContributed; uint256 public LPperETHUnit; bool public LPGenerationCompleted; function addLiquidityToUniswapCORExWETHPair() public { require(liquidityGenerationOngoing() == false, "Liquidity generation onging"); require(LPGenerationCompleted == false, "Liquidity generation already finished"); totalETHContributed = address(this).balance; IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); console.log("Balance of this", totalETHContributed / 1e18); address WETH = uniswapRouterV2.WETH(); require(address(this).balance == 0 , "Transfer Failed"); IWETH(WETH).transfer(address(pair),totalETHContributed); _balances[address(pair)] = _balances[address(this)]; _balances[address(this)] = 0; pair.mint(address(this)); totalLPTokensMinted = pair.balanceOf(address(this)); console.log("Total tokens minted",totalLPTokensMinted); require(totalLPTokensMinted != 0 , "LP creation failed"); console.log("Total per LP token", LPperETHUnit); require(LPperETHUnit != 0 , "LP creation failed"); LPGenerationCompleted = true; } mapping (address => uint) public ethContributed; IWETH(WETH).deposit{value : totalETHContributed}(); function addLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement) public payable { require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided"); emit LiquidityAddition(msg.sender, msg.value); } function claimLPTokens() public { require(LPGenerationCompleted, "Event not over yet"); require(ethContributed[msg.sender] > 0 , "Nothing to claim, move along"); IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18); ethContributed[msg.sender] = 0; emit LPTokenClaimed(msg.sender, amountLPToTransfer); } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function setShouldTransferChecker(address _transferCheckerAddress) public onlyOwner { transferCheckerAddress = _transferCheckerAddress; } address public transferCheckerAddress; function setFeeDistributor(address _feeDistributor) public onlyOwner { feeDistributor = _feeDistributor; } address public feeDistributor; 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" ); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferCheckerAddress).calculateAmountsAfterFee(sender, recipient, amount); console.log("Sender is :" , sender, "Recipent is :", recipient); console.log("amount is ", amount); require(transferToAmount.add(transferToFeeDistributorAmount) == amount, "Math broke, does gravity still work?"); _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); if(feeDistributor != address(0)){ ICoreVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount); } } } 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" ); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferCheckerAddress).calculateAmountsAfterFee(sender, recipient, amount); console.log("Sender is :" , sender, "Recipent is :", recipient); console.log("amount is ", amount); require(transferToAmount.add(transferToFeeDistributorAmount) == amount, "Math broke, does gravity still work?"); _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); if(feeDistributor != address(0)){ ICoreVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount); } } } 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" ); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferCheckerAddress).calculateAmountsAfterFee(sender, recipient, amount); console.log("Sender is :" , sender, "Recipent is :", recipient); console.log("amount is ", amount); require(transferToAmount.add(transferToFeeDistributorAmount) == amount, "Math broke, does gravity still work?"); _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); if(feeDistributor != address(0)){ ICoreVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } ) internal virtual {} }
16,262,203
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 20096, 10377, 654, 39, 3462, 353, 1772, 16, 2120, 38, 10377, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 871, 511, 18988, 24237, 30296, 12, 2867, 8808, 3046, 16, 2254, 460, 1769, 203, 565, 871, 511, 52, 1345, 9762, 329, 12, 2867, 3046, 16, 2254, 460, 1769, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 1071, 6835, 1685, 4921, 31, 203, 203, 203, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 2172, 7365, 12, 2867, 4633, 16, 1758, 3272, 13, 2713, 288, 203, 3639, 389, 529, 273, 315, 91, 89, 23121, 932, 14432, 203, 3639, 389, 7175, 273, 315, 23121, 89, 304, 85, 2779, 383, 14432, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 81, 474, 12, 2867, 12, 2211, 3631, 2172, 3088, 1283, 1769, 203, 3639, 6835, 1685, 4921, 273, 1203, 18, 5508, 31, 203, 3639, 752, 984, 291, 91, 438, 4154, 6376, 2758, 5621, 203, 565, 289, 203, 2 ]
./full_match/1/0x7e5E4eB92aE9e5E47a04e832d029a2E4186DD750/sources/Users/elenaderymova/projects/work/4irelabs/rock3t-prototype-contracts/contracts/LiquidVault.sol
Dev note: increase gasLimit to be able run up to 100 iterations
function insertUnclaimedBatchFor(address[] memory _holders, uint[] memory _amounts, uint[] memory _timestamps) public onlyOwner { require(!batchInsertionFinished, "R3T: Manual batch insertion is no longer allowed."); require( _holders.length == _holders.length && _timestamps.length == _holders.length, "R3T: Batch arrays should have same length" ); require(_holders.length <= 100, 'R3T: loop limitations reached'); for (uint i = 0; i < _holders.length; i++) { lockedLP[_holders[i]].push( LPbatch({ holder: _holders[i], amount: _amounts[i], timestamp: _timestamps[i], claimed: false }) ); } }
17,114,324
[ 1, 8870, 4721, 30, 10929, 16189, 3039, 358, 506, 7752, 1086, 731, 358, 2130, 11316, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2243, 984, 14784, 329, 4497, 1290, 12, 2867, 8526, 3778, 389, 9000, 16, 2254, 8526, 3778, 389, 8949, 87, 16, 2254, 8526, 3778, 389, 25459, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 5303, 29739, 10577, 16, 315, 54, 23, 56, 30, 8660, 1462, 2581, 12626, 353, 1158, 7144, 2935, 1199, 1769, 203, 3639, 2583, 12, 203, 5411, 389, 9000, 18, 2469, 422, 389, 9000, 18, 2469, 597, 389, 25459, 18, 2469, 422, 389, 9000, 18, 2469, 16, 203, 5411, 315, 54, 23, 56, 30, 5982, 5352, 1410, 1240, 1967, 769, 6, 203, 3639, 11272, 203, 3639, 2583, 24899, 9000, 18, 2469, 1648, 2130, 16, 296, 54, 23, 56, 30, 2798, 31810, 8675, 8284, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 9000, 18, 2469, 31, 277, 27245, 288, 203, 5411, 8586, 14461, 63, 67, 9000, 63, 77, 65, 8009, 6206, 12, 203, 7734, 511, 52, 5303, 12590, 203, 10792, 10438, 30, 389, 9000, 63, 77, 6487, 203, 10792, 3844, 30, 389, 8949, 87, 63, 77, 6487, 203, 10792, 2858, 30, 389, 25459, 63, 77, 6487, 203, 10792, 7516, 329, 30, 629, 203, 7734, 289, 13, 203, 5411, 11272, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.7; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import './utils/Deployer.sol'; import './interfaces/IERC20Template.sol'; /** * @title DTFactory contract * @author Ocean Protocol Team * * @dev Implementation of Ocean DataTokens Factory * * DTFactory deploys DataToken proxy contracts. * New DataToken proxy contracts are links to the template contract's bytecode. * Proxy contract functionality is based on Ocean Protocol custom implementation of ERC1167 standard. */ contract DTFactory is Deployer { address private tokenTemplate; address private communityFeeCollector; uint256 private currentTokenCount = 1; event TokenCreated( address indexed newTokenAddress, address indexed templateAddress, string indexed tokenName ); event TokenRegistered( address indexed tokenAddress, string tokenName, string tokenSymbol, uint256 tokenCap, address indexed registeredBy, string indexed blob ); /** * @dev constructor * Called on contract deployment. Could not be called with zero address parameters. * @param _template refers to the address of a deployed DataToken contract. * @param _collector refers to the community fee collector address */ constructor( address _template, address _collector ) public { require( _template != address(0) && _collector != address(0), 'DTFactory: Invalid template token/community fee collector address' ); tokenTemplate = _template; communityFeeCollector = _collector; } /** * @dev Deploys new DataToken proxy contract. * Template contract address could not be a zero address. * @param blob any string that hold data/metadata for the new token * @param name token name * @param symbol token symbol * @param cap the maximum total supply * @return address of a new proxy DataToken contract */ function createToken( string memory blob, string memory name, string memory symbol, uint256 cap ) public returns (address token) { require( cap != 0, 'DTFactory: zero cap is not allowed' ); token = deploy(tokenTemplate); require( token != address(0), 'DTFactory: Failed to perform minimal deploy of a new token' ); IERC20Template tokenInstance = IERC20Template(token); require( tokenInstance.initialize( name, symbol, msg.sender, cap, blob, communityFeeCollector ), 'DTFactory: Unable to initialize token instance' ); emit TokenCreated(token, tokenTemplate, name); emit TokenRegistered( token, name, symbol, cap, msg.sender, blob ); currentTokenCount += 1; } /** * @dev get the current token count. * @return the current token count */ function getCurrentTokenCount() external view returns (uint256) { return currentTokenCount; } /** * @dev get the token template address * @return the template address */ function getTokenTemplate() external view returns (address) { return tokenTemplate; } }
* @title DTFactory contract @author Ocean Protocol Team @dev Implementation of Ocean DataTokens Factory DTFactory deploys DataToken proxy contracts. New DataToken proxy contracts are links to the template contract's bytecode. Proxy contract functionality is based on Ocean Protocol custom implementation of ERC1167 standard./
contract DTFactory is Deployer { address private tokenTemplate; address private communityFeeCollector; uint256 private currentTokenCount = 1; event TokenCreated( address indexed newTokenAddress, address indexed templateAddress, string indexed tokenName ); event TokenRegistered( address indexed tokenAddress, string tokenName, string tokenSymbol, uint256 tokenCap, address indexed registeredBy, string indexed blob ); constructor( address _template, address _collector ) public { require( _template != address(0) && _collector != address(0), 'DTFactory: Invalid template token/community fee collector address' ); tokenTemplate = _template; communityFeeCollector = _collector; } function createToken( string memory blob, string memory name, string memory symbol, uint256 cap ) public returns (address token) { require( cap != 0, 'DTFactory: zero cap is not allowed' ); token = deploy(tokenTemplate); require( token != address(0), 'DTFactory: Failed to perform minimal deploy of a new token' ); IERC20Template tokenInstance = IERC20Template(token); require( tokenInstance.initialize( name, symbol, msg.sender, cap, blob, communityFeeCollector ), 'DTFactory: Unable to initialize token instance' ); emit TokenCreated(token, tokenTemplate, name); emit TokenRegistered( token, name, symbol, cap, msg.sender, blob ); currentTokenCount += 1; } function getCurrentTokenCount() external view returns (uint256) { return currentTokenCount; } function getTokenTemplate() external view returns (address) { return tokenTemplate; } }
2,567,424
[ 1, 9081, 1733, 6835, 225, 531, 31393, 4547, 10434, 225, 25379, 434, 531, 31393, 1910, 5157, 7822, 1377, 10696, 1733, 5993, 383, 1900, 1910, 1345, 2889, 20092, 18, 1377, 1166, 1910, 1345, 2889, 20092, 854, 4716, 358, 326, 1542, 6835, 1807, 22801, 18, 1377, 7659, 6835, 14176, 353, 2511, 603, 531, 31393, 4547, 1679, 4471, 434, 4232, 39, 20562, 27, 4529, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 10696, 1733, 353, 7406, 264, 288, 203, 565, 1758, 3238, 1147, 2283, 31, 203, 565, 1758, 3238, 19833, 14667, 7134, 31, 203, 565, 2254, 5034, 3238, 23719, 1380, 273, 404, 31, 203, 203, 565, 871, 3155, 6119, 12, 203, 3639, 1758, 8808, 394, 1345, 1887, 16, 203, 3639, 1758, 8808, 1542, 1887, 16, 203, 3639, 533, 8808, 1147, 461, 203, 565, 11272, 203, 203, 565, 871, 3155, 10868, 12, 203, 3639, 1758, 8808, 1147, 1887, 16, 203, 3639, 533, 1147, 461, 16, 203, 3639, 533, 1147, 5335, 16, 203, 3639, 2254, 5034, 1147, 4664, 16, 203, 3639, 1758, 8808, 4104, 858, 16, 203, 3639, 533, 8808, 4795, 203, 565, 11272, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 3202, 16, 203, 3639, 1758, 389, 21356, 203, 203, 565, 262, 1071, 288, 203, 3639, 2583, 12, 203, 5411, 389, 3202, 480, 1758, 12, 20, 13, 597, 203, 5411, 389, 21356, 480, 1758, 12, 20, 3631, 203, 5411, 296, 9081, 1733, 30, 1962, 1542, 1147, 19, 20859, 14036, 8543, 1758, 11, 203, 3639, 11272, 203, 3639, 1147, 2283, 273, 389, 3202, 31, 203, 3639, 19833, 14667, 7134, 273, 389, 21356, 31, 203, 565, 289, 203, 203, 565, 445, 752, 1345, 12, 203, 3639, 533, 3778, 4795, 16, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 2254, 5034, 3523, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1135, 261, 2867, 1147, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 3523, 480, 374, 16, 203, 5411, 296, 9081, 2 ]
./full_match/80001/0x14dd9993Cd065f34B2a892EfaaAdbe03Cc200702/sources/StakingContract.sol
0.05 MATIC on POLYGON
uint256 private PREMIUM_PRICE = 0.05 ether;
854,804
[ 1, 20, 18, 6260, 490, 11781, 603, 19383, 30317, 673, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 7071, 7492, 2799, 67, 7698, 1441, 273, 374, 18, 6260, 225, 2437, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x20E4dBa7E96ea3890B4dDf85a8fdEDf584c50b8e/sources/VampireToken.sol
VampireToken with Governance.
contract VampireToken is BEP20('Vampire Token', 'VAMPIRE') { function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { require(amount == sendAmount + burnAmount, "Burn value invalid"); super._burn(sender, burnAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } else{ super._transfer(sender, recipient, amount); } }
11,091,420
[ 1, 58, 931, 577, 1345, 598, 611, 1643, 82, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 776, 931, 577, 1345, 353, 9722, 52, 3462, 2668, 58, 931, 577, 3155, 2187, 296, 58, 2192, 1102, 862, 6134, 288, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 389, 8501, 15608, 815, 12, 2867, 12, 20, 3631, 389, 3771, 1332, 815, 63, 67, 869, 6487, 389, 8949, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 2713, 5024, 3849, 288, 203, 5411, 2583, 12, 8949, 422, 1366, 6275, 397, 18305, 6275, 16, 315, 38, 321, 460, 2057, 8863, 203, 5411, 2240, 6315, 70, 321, 12, 15330, 16, 18305, 6275, 1769, 203, 5411, 2240, 6315, 13866, 12, 15330, 16, 8027, 16, 1366, 6275, 1769, 203, 5411, 3844, 273, 1366, 6275, 31, 203, 3639, 289, 203, 3639, 469, 95, 203, 5411, 2240, 6315, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 289, 203, 540, 203, 6647, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.0; import "../Tokens/StandardToken.sol"; /// @title Outcome token contract - Issuing and revoking outcome tokens /// @author Stefan George - <[email protected]> contract OutcomeToken is StandardToken { using Math for *; /* * Events */ event Issuance(address indexed owner, uint amount); event Revocation(address indexed owner, uint amount); /* * Storage */ address public eventContract; /* * Modifiers */ modifier isEventContract () { // Only event contract is allowed to proceed require(msg.sender == eventContract); _; } /* * Public functions */ /// @dev Constructor sets events contract address constructor() public { eventContract = msg.sender; } /// @dev Events contract issues new tokens for address. Returns success /// @param _for Address of receiver /// @param outcomeTokenCount Number of tokens to issue function issue(address _for, uint outcomeTokenCount) public isEventContract { balances[_for] = balances[_for].add(outcomeTokenCount); totalTokens = totalTokens.add(outcomeTokenCount); emit Issuance(_for, outcomeTokenCount); } /// @dev Events contract revokes tokens for address. Returns success /// @param _for Address of token holder /// @param outcomeTokenCount Number of tokens to revoke function revoke(address _for, uint outcomeTokenCount) public isEventContract { balances[_for] = balances[_for].sub(outcomeTokenCount); totalTokens = totalTokens.sub(outcomeTokenCount); emit Revocation(_for, outcomeTokenCount); } }
@dev Events contract revokes tokens for address. Returns success @param _for Address of token holder @param outcomeTokenCount Number of tokens to revoke
function revoke(address _for, uint outcomeTokenCount) public isEventContract { balances[_for] = balances[_for].sub(outcomeTokenCount); totalTokens = totalTokens.sub(outcomeTokenCount); emit Revocation(_for, outcomeTokenCount); }
1,831,230
[ 1, 3783, 6835, 5588, 601, 281, 2430, 364, 1758, 18, 2860, 2216, 225, 389, 1884, 5267, 434, 1147, 10438, 225, 12884, 1345, 1380, 3588, 434, 2430, 358, 18007, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18007, 12, 2867, 389, 1884, 16, 2254, 12884, 1345, 1380, 13, 203, 3639, 1071, 203, 3639, 15805, 8924, 203, 565, 288, 203, 3639, 324, 26488, 63, 67, 1884, 65, 273, 324, 26488, 63, 67, 1884, 8009, 1717, 12, 21672, 1345, 1380, 1769, 203, 3639, 2078, 5157, 273, 2078, 5157, 18, 1717, 12, 21672, 1345, 1380, 1769, 203, 3639, 3626, 14477, 4431, 24899, 1884, 16, 12884, 1345, 1380, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x2ef5240F19B45C02c6eb53211e034bD504Ea1f82/sources/DSProtestPause.sol
a tx can be protested against if max 1/2 of the time until earliest execution has passed
uint256 constant public protestEnd = 500;
9,087,975
[ 1, 69, 2229, 848, 506, 11121, 3149, 5314, 309, 943, 404, 19, 22, 434, 326, 813, 3180, 20674, 4588, 711, 2275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 5381, 1071, 450, 3813, 1638, 9079, 273, 6604, 31, 5375, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20() public { uint256 initialSupply = 1000000000; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "ε°ι’»ι£Ž"; // Set the name for display purposes symbol = "ε°ι’»ι£Ž"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender&#39;s allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
Public variables of the token 18 decimals is the strongly suggested default, avoid changing it This creates an array with all balances This generates a public event on the blockchain that will notify clients This notifies clients about the amount burnt
contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } function TokenERC20() public { uint256 initialSupply = 1000000000; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { emit Burn(_from, _value); return true; } }
6,659,009
[ 1, 4782, 3152, 434, 326, 1147, 6549, 15105, 353, 326, 11773, 715, 22168, 805, 16, 4543, 12770, 518, 1220, 3414, 392, 526, 598, 777, 324, 26488, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 654, 39, 3462, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 5831, 1147, 18241, 288, 445, 6798, 23461, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2316, 16, 1731, 389, 7763, 751, 13, 3903, 31, 289, 203, 565, 445, 3155, 654, 39, 3462, 1435, 1071, 288, 203, 3639, 2254, 5034, 2172, 3088, 1283, 273, 15088, 3784, 31, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 869, 65, 397, 389, 1132, 1545, 11013, 951, 63, 67, 869, 19226, 203, 3639, 2254, 2416, 38, 26488, 273, 11013, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 15533, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 3639, 2 ]
./full_match/1/0xE7B4451e568CFeCa708aD17dFE0918D0905dc811/sources/contracts/vault-base/VaultBaseInternal.sol
The Executor runs as the Vault. I'm not sure this is ideal but it makes writing executors easy Other solutions are 1. The executor returns transactions to be executed which are then assembly called by the this 2. We write the executor code in the vault Get value before for CPIT Make the external call Get value after for CPIT We use max value here to exclude gmx exit fees from calculation
function _execute( ExecutorIntegration integration, bytes memory encodedWithSelectorPayload ) internal { (, uint valueBefore) = _getVaultValue(); VaultBaseStorage.Layout storage l = VaultBaseStorage.layout(); address executor = l.registry.executors(integration); require(executor != address(0), 'no executor'); Call._delegate(executor, encodedWithSelectorPayload); (, uint valueAfter) = _getVaultValue(); _updatePriceImpact( valueBefore, valueAfter, _registry().maxCpitBips(l.riskProfile) ); }
3,152,422
[ 1, 1986, 13146, 7597, 487, 326, 17329, 18, 467, 17784, 486, 3071, 333, 353, 23349, 1496, 518, 7297, 7410, 1196, 13595, 12779, 4673, 22567, 854, 404, 18, 1021, 6601, 1135, 8938, 358, 506, 7120, 1492, 854, 1508, 19931, 2566, 635, 326, 333, 576, 18, 1660, 1045, 326, 6601, 981, 316, 326, 9229, 968, 460, 1865, 364, 385, 1102, 56, 4344, 326, 3903, 745, 968, 460, 1839, 364, 385, 1102, 56, 1660, 999, 943, 460, 2674, 358, 4433, 314, 11023, 2427, 1656, 281, 628, 11096, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8837, 12, 203, 3639, 13146, 15372, 12040, 16, 203, 3639, 1731, 3778, 3749, 1190, 4320, 6110, 203, 565, 262, 2713, 288, 203, 3639, 261, 16, 2254, 460, 4649, 13, 273, 389, 588, 12003, 620, 5621, 203, 203, 3639, 17329, 2171, 3245, 18, 3744, 2502, 328, 273, 17329, 2171, 3245, 18, 6741, 5621, 203, 3639, 1758, 6601, 273, 328, 18, 9893, 18, 4177, 13595, 12, 27667, 1769, 203, 3639, 2583, 12, 21097, 480, 1758, 12, 20, 3631, 296, 2135, 6601, 8284, 203, 3639, 3049, 6315, 22216, 12, 21097, 16, 3749, 1190, 4320, 6110, 1769, 203, 203, 3639, 261, 16, 2254, 460, 4436, 13, 273, 389, 588, 12003, 620, 5621, 203, 3639, 389, 2725, 5147, 22683, 621, 12, 203, 5411, 460, 4649, 16, 203, 5411, 460, 4436, 16, 203, 5411, 389, 9893, 7675, 1896, 28954, 305, 38, 7146, 12, 80, 18, 86, 10175, 4029, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.2; import "./KryptoRealState.sol"; import "../zokrates/code/square/verifier.sol"; /** * @dev Contract module to mint KryptoRealState tokens. Sellers are * entitle to list their properties only upon presenting a valid * proof of ownership based on zk-SNARKs. * * Tokens are implemented as in the ERC721 standard. * see https://eips.ethereum.org/EIPS/eip-721 */ contract ProofVerifierKRS is KryptoRealState { SquareVerifier private squareVerifier; struct Solution { bytes32 key; address prover; bool redeemable; bool exists; } // Array with all solutions, used for enumeration Solution[] private _solutions; // Mapping from solution key to the position in the solutions array mapping(bytes32 => uint256) private _solutionsIndex; event ProofVerified(bytes32 key, address indexed prover); event TokenMinted(address to, bytes32 key, uint256 tokenId); constructor(address verifier) public KryptoRealState() { squareVerifier = SquareVerifier(verifier); } /** * @dev Submit a candidate ownership-proof for validation. * * The proof consists on the points of the elliptic curve * corresponding to the input. */ function submitOwnershipProof( uint256[2] calldata a, uint256[2][2] calldata b, uint256[2] calldata c, uint256[2] calldata input ) external { bytes32 key = keccak256( abi.encodePacked( a[0], a[1], b[0][0], b[0][1], b[1][0], b[1][1], c[0], c[1], input[0], input[1] ) ); require(!_exists(key), "KryptoRealStateZKP: solution exists already"); require( _isValidProof(a, b, c, input), "KryptoRealStateZKP: solution proof is not valid for that input" ); _solutions.push(Solution(key, msg.sender, true, true)); _solutionsIndex[key] = _solutions.length - 1; emit ProofVerified(key, msg.sender); } /** * @dev Mints a new token if a prover has previously submitted a valid * proof of ownership. */ function mint(bytes32 key) external { require( _exists(key), "KryptoRealStateZKP: solution key does not exist" ); require( _redeemable(key), "KryptoRealStateZKP: solution key is not redeemable" ); require( _solution(key).prover == msg.sender, "KryptoRealStateZKP: only the prover can mint a token" ); _redeemSolution(key); super.mint(msg.sender, uint256(key)); emit TokenMinted(msg.sender, key, uint256(key)); } function _solution(bytes32 key) internal view returns (Solution memory) { uint256 index = _solutionsIndex[key]; return _solutions[index]; } function _redeemable(bytes32 key) internal view returns (bool) { if (_solutions.length == 0) { return false; } uint256 index = _solutionsIndex[key]; return _solutions[index].redeemable && _solutions[index].key == key; } function _exists(bytes32 key) internal view returns (bool) { if (_solutions.length == 0) { return false; } uint256 index = _solutionsIndex[key]; return _solutions[index].exists && _solutions[index].key == key; } function _redeemSolution(bytes32 key) internal { uint256 index = _solutionsIndex[key]; _solutions[index].redeemable = false; } function _isValidProof( uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c, uint256[2] memory input ) internal view returns (bool) { return squareVerifier.verifyTx(a, b, c, input); } }
Array with all solutions, used for enumeration
Solution[] private _solutions;
1,005,750
[ 1, 1076, 598, 777, 22567, 16, 1399, 364, 16836, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 29172, 8526, 3238, 389, 18281, 6170, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa93D3C92D2CfeA09b9c247444A0C1dB5F7707F78/sources/SHIBEMPEROR.sol
SHIBEMPEROR Taxes 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488DBalances tracker
contract SHIBEMPEROR is Context,IERC20, Ownable{ using Address for address; string private _name = "SHIBEMPEROR"; string private _symbol = "SHIBEMP"; uint8 private _decimals = 18; uint256 totalFeeFortx = 0; uint256 maxWalletTreshold = 2; uint256 maxTxTreshold = 1; uint256 private swapTreshold =1; uint256 public requiredTokensToSwap = _totalSupply * swapTreshold /1000; mapping (address => uint256) private _balances; mapping (address => bool) private _excludedFromFees; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public automatedMarketMakerPairs; address _owner; address payable public marketingAddress = payable(0x2CE77dFB77AE61Ad87fE23f4747aE2e2dE011B3B); uint256 maxTxAmount = _totalSupply*maxTxTreshold/100; mapping (address => bool) botWallets; bool botTradeEnabled = false; bool checkWalletSize = true; mapping (address => bool) private _liquidityHolders; mapping (address => bool) private presaleAddresses; uint256 private buyprevLiqFee = 0; uint256 private buyPrevmktFee = 0; uint256 SHIBEMPERORCOINDaycooldown = 0; bool private tradeEnabled = false; uint256 private sellliqFee = 1; uint256 private sellprevLiqFee = 0; uint256 private sellmktFee = 29; uint256 private sellPrevmktFee = 0; bool public inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; uint256 private mktTokens = 0; uint256 private liqTokens = 0; event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event tokensSwappedDuringTokenomics(uint256 amount); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); IUniswapV2Router02 _router; address public uniswapV2Pair; modifier lockTheSwap{ inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor(){ _balances[_msgSender()] = _totalSupply; IUniswapV2Router02 _uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniRouter.factory()) .createPair(address(this), _uniRouter.WETH()); _excludedFromFees[owner()] = true; _router = _uniRouter; _liquidityHolders[address(_router)] = true; _liquidityHolders[owner()] = true; _liquidityHolders[address(this)] = true; _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); emit Transfer(address(0),_msgSender(),_totalSupply); } receive() external payable{} function getOwner()external view returns(address){ return owner(); } function currentmktTokens() external view returns (uint256){ return mktTokens; } function currentLiqTokens() external view returns (uint256){ return liqTokens; } function totalSupply() external view override returns (uint256){ return _totalSupply; } function balanceOf(address account) public view override returns (uint256){ return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool){ _transfer(_msgSender(),recipient,amount); return true; } function allowance(address owner, address spender) external view override returns (uint256){ return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool){ _approve(_msgSender(),spender,amount); return true; } function decimals()external view returns(uint256){ return _decimals; } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory){ return _symbol; } function updateMaxTxTreshold(uint256 newVal) public onlyOwner{ maxTxTreshold = newVal; } function updateMaxWalletTreshold(uint256 newVal) public onlyOwner{ maxWalletTreshold = newVal; maxWalletAmount = _totalSupply*maxWalletTreshold/100; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool){ require(amount <= _allowances[sender][_msgSender()], "ERC20: transfer amount exceeds allowance"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } function COINDay() public onlyOwner{ require(block.timestamp > SHIBEMPERORCOINDaycooldown, "You cant call SHIBEMPERORCOINCoinDay more than once a day"); buyPrevmktFee = buymktFee; buyprevLiqFee = buyliqFee; buyliqFee = 0; buymktFee = 0; } function SHIBEMPERORCOINCoinDayOver() public onlyOwner{ buyliqFee = buyprevLiqFee; buymktFee = buyPrevmktFee; SHIBEMPERORCOINDaycooldown = block.timestamp + 86400; } function addBotWallet (address payable detectedBot, bool isBot) public onlyOwner{ botWallets[detectedBot] = isBot; } function currentbuyliqFee() public view returns (uint256){ return buyliqFee; } function currentbuymktfee() public view returns (uint256){ return buymktFee; } function currentsellLiqFee() public view returns (uint256){ return sellliqFee; } function currentsellmktfee() public view returns (uint256){ return sellmktFee; } function currentThresholdInt()public view returns (uint256){ return currentThreshold; } function isExcluded(address toCheck)public view returns (bool){ return _excludedFromFees[toCheck]; } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function swapForTokenomics(uint256 balanceToswap) private lockTheSwap{ swapAndLiquify(liqTokens); swapTokensForETHmkt(mktTokens); emit tokensSwappedDuringTokenomics(balanceToswap); mktTokens = 0; liqTokens = 0; } function addLimitExempt(address newAddress)external onlyOwner{ _liquidityHolders[newAddress] = true; } function swapTokensForETHmkt(uint256 amount)private { address[] memory path = new address[](2); path[0] = address(this); path[1] = _router.WETH(); _approve(address(this), address(_router), amount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, path, marketingAddress, block.timestamp ); } function unstuckTokens (IERC20 tokenToClear, address payable destination, uint256 amount) public onlyOwner{ tokenToClear.transfer(destination, amount); } function unstuckETH(address payable destination) public onlyOwner{ uint256 ethBalance = address(this).balance; payable(destination).transfer(ethBalance); } function tradeStatus(bool status) public onlyOwner{ tradeEnabled = status; } function swapAndLiquify(uint256 liqTokensPassed) private { uint256 half = liqTokensPassed / 2; uint256 otherHalf = liqTokensPassed - half; uint256 initialBalance = address(this).balance; swapTokensForETH(half); uint256 newBalance = address(this).balance - (initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half,newBalance,otherHalf); } function swapTokensForETH(uint256 tokenAmount) private{ address[] memory path = new address[](2); path[0] = address(this); path[1] = _router.WETH(); _approve(address(this), address(_router), tokenAmount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount,uint256 ethAmount) private{ _approve(address(this), address(_router), tokenAmount); address(this), tokenAmount, 0, 0, block.timestamp ); } _router.addLiquidityETH{value:ethAmount}( function _approve(address owner,address spender, uint256 amount) internal{ require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function addToExcluded(address toExclude) public onlyOwner{ _excludedFromFees[toExclude] = true; } function removeFromExcluded(address toRemove) public onlyOwner{ _excludedFromFees[toRemove] = false; } function excludePresaleAddresses(address router, address presale) external onlyOwner { _liquidityHolders[address(router)] = true; _liquidityHolders[presale] = true; presaleAddresses[address(router)] = true; presaleAddresses[presale] = true; } function endPresaleStatus() public onlyOwner{ buymktFee = 4; buyliqFee = 2; sellmktFee = 4; sellliqFee = 2; setSwapAndLiquify(true); } function updateThreshold(uint newThreshold) public onlyOwner{ currentThreshold = newThreshold; } function setSwapAndLiquify(bool _enabled) public onlyOwner{ swapAndLiquifyEnabled = _enabled; } function setMktAddress(address newAddress) external onlyOwner{ marketingAddress = payable(newAddress); } function transferAssetsETH(address payable to, uint256 amount) internal{ to.transfer(amount); } 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 updatecurrentbuyliqFee(uint256 newAmount) public onlyOwner{ buyliqFee = newAmount; } function updatecurrentbuymktfee(uint256 newAmount) public onlyOwner{ buymktFee= newAmount; } function updatecurrentsellLiqFee(uint256 newAmount) public onlyOwner{ sellliqFee= newAmount; } function updatecurrentsellmktfee(uint256 newAmount)public onlyOwner{ sellmktFee= newAmount; } function currentMaxWallet() public view returns(uint256){ return maxWalletAmount; } function currentMaxTx() public view returns(uint256){ return maxTxAmount; } function updateSwapTreshold(uint256 newVal) public onlyOwner{ swapTreshold = newVal; requiredTokensToSwap = _totalSupply*swapTreshold/1000; } function currentTradeStatus() public view returns (bool){ return tradeEnabled; } function currentSwapTreshold() public view returns(uint256){ return swapTreshold; } function currentTokensToSwap() public view returns(uint256){ return requiredTokensToSwap; } }
11,017,991
[ 1, 2664, 13450, 3375, 3194, 916, 399, 10855, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 2290, 26488, 9745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6122, 13450, 3375, 3194, 916, 353, 1772, 16, 45, 654, 39, 3462, 16, 14223, 6914, 95, 203, 9940, 5267, 364, 1758, 31, 203, 1080, 3238, 389, 529, 273, 315, 2664, 13450, 3375, 3194, 916, 14432, 203, 1080, 3238, 389, 7175, 273, 315, 2664, 13450, 3375, 52, 14432, 203, 11890, 28, 3238, 389, 31734, 273, 6549, 31, 203, 11890, 5034, 2078, 14667, 42, 499, 92, 273, 374, 31, 203, 2254, 5034, 943, 16936, 56, 3444, 273, 576, 31, 203, 11890, 5034, 943, 4188, 56, 3444, 273, 404, 31, 203, 11890, 5034, 3238, 7720, 56, 3444, 273, 21, 31, 203, 11890, 5034, 1071, 1931, 5157, 774, 12521, 273, 389, 4963, 3088, 1283, 380, 7720, 56, 3444, 342, 18088, 31, 203, 6770, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 6770, 261, 2867, 516, 1426, 13, 3238, 389, 24602, 1265, 2954, 281, 31, 203, 6770, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 6770, 261, 2867, 516, 1426, 13, 1071, 18472, 690, 3882, 278, 12373, 10409, 31, 203, 2867, 389, 8443, 31, 203, 2867, 8843, 429, 1071, 13667, 310, 1887, 273, 8843, 429, 12, 20, 92, 22, 1441, 4700, 72, 22201, 4700, 16985, 9498, 1871, 11035, 74, 41, 4366, 74, 24, 5608, 27, 69, 41, 22, 73, 22, 72, 41, 1611, 21, 38, 23, 38, 1769, 203, 11890, 5034, 943, 4188, 6275, 273, 389, 4963, 3088, 1283, 14, 1896, 4188, 56, 3444, 19, 6625, 31, 203, 6770, 261, 2867, 516, 1426, 13, 2512, 26558, 2 ]
pragma solidity ^0.4.15; /* 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. */ contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } contract basicToken { function balanceOf(address) public view returns (uint256); function transfer(address, uint256) public returns (bool); function transferFrom(address, address, uint256) public returns (bool); function approve(address, uint256) public returns (bool); function allowance(address, address) public view returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ERC20Standard is basicToken{ mapping (address => mapping (address => uint256)) allowed; mapping (address => uint256) public balances; /* Send coins */ function transfer(address _to, uint256 _value) public returns (bool success){ require (_to != 0x0); // Prevent transfer to 0x0 address require (balances[msg.sender] > _value); // Check if the sender has enough require (balances[_to] + _value > balances[_to]); // Check for overflows _transfer(msg.sender, _to, _value); // Perform actually transfer Transfer(msg.sender, _to, _value); // Trigger Transfer event return true; } /* Use admin powers to send from a users account */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){ require (_to != 0x0); // Prevent transfer to 0x0 address require (balances[msg.sender] > _value); // Check if the sender has enough require (balances[_to] + _value > balances[_to]); // Check for overflows require (allowed[_from][msg.sender] >= _value); // Only allow if sender is allowed to do this _transfer(msg.sender, _to, _value); // Perform actually transfer Transfer(msg.sender, _to, _value); // Trigger Transfer event return true; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient } /* Get balance of an account */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /* Approve an address to have admin power to use transferFrom */ 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) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract HydroToken is ERC20Standard, owned{ event Authenticate(uint partnerId, address indexed from, uint value); // Event for when an address is authenticated event Whitelist(uint partnerId, address target, bool whitelist); // Event for when an address is whitelisted to authenticate event Burn(address indexed burner, uint256 value); // Event for when tokens are burned struct partnerValues { uint value; uint challenge; } struct hydrogenValues { uint value; uint timestamp; } string public name = "Hydro"; string public symbol = "HYDRO"; uint8 public decimals = 18; uint256 public totalSupply; /* This creates an array of all whitelisted addresses * Must be whitelisted to be able to utilize auth */ mapping (uint => mapping (address => bool)) public whitelist; mapping (uint => mapping (address => partnerValues)) public partnerMap; mapping (uint => mapping (address => hydrogenValues)) public hydroPartnerMap; /* Initializes contract with initial supply tokens to the creator of the contract */ function HydroToken() public { totalSupply = 11111111111 * 10**18; balances[msg.sender] = totalSupply; // Give the creator all initial tokens } /* Function to whitelist partner address. Can only be called by owner */ function whitelistAddress(address _target, bool _whitelistBool, uint _partnerId) public onlyOwner { whitelist[_partnerId][_target] = _whitelistBool; Whitelist(_partnerId, _target, _whitelistBool); } /* Function to authenticate user Restricted to whitelisted partners */ function authenticate(uint _value, uint _challenge, uint _partnerId) public { require(whitelist[_partnerId][msg.sender]); // Make sure the sender is whitelisted require(balances[msg.sender] > _value); // Check if the sender has enough require(hydroPartnerMap[_partnerId][msg.sender].value == _value); updatePartnerMap(msg.sender, _value, _challenge, _partnerId); transfer(owner, _value); Authenticate(_partnerId, msg.sender, _value); } function burn(uint256 _value) public onlyOwner { require(balances[msg.sender] > _value); balances[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); } function checkForValidChallenge(address _sender, uint _partnerId) public view returns (uint value){ if (hydroPartnerMap[_partnerId][_sender].timestamp > block.timestamp){ return hydroPartnerMap[_partnerId][_sender].value; } return 1; } /* Function to update the partnerValuesMap with their amount and challenge string */ function updatePartnerMap(address _sender, uint _value, uint _challenge, uint _partnerId) internal { partnerMap[_partnerId][_sender].value = _value; partnerMap[_partnerId][_sender].challenge = _challenge; } /* Function to update the hydrogenValuesMap. Called exclusively from the Hydro API */ function updateHydroMap(address _sender, uint _value, uint _partnerId) public onlyOwner { hydroPartnerMap[_partnerId][_sender].value = _value; hydroPartnerMap[_partnerId][_sender].timestamp = block.timestamp + 1 days; } /* Function called by Hydro API to check if the partner has validated * The partners value and data must match and it must be less than a day since the last authentication */ function validateAuthentication(address _sender, uint _challenge, uint _partnerId) public constant returns (bool _isValid) { if (partnerMap[_partnerId][_sender].value == hydroPartnerMap[_partnerId][_sender].value && block.timestamp < hydroPartnerMap[_partnerId][_sender].timestamp && partnerMap[_partnerId][_sender].challenge == _challenge){ return true; } return false; } }
Function called by Hydro API to check if the partner has validated The partners value and data must match and it must be less than a day since the last authentication/
function validateAuthentication(address _sender, uint _challenge, uint _partnerId) public constant returns (bool _isValid) { if (partnerMap[_partnerId][_sender].value == hydroPartnerMap[_partnerId][_sender].value && block.timestamp < hydroPartnerMap[_partnerId][_sender].timestamp && partnerMap[_partnerId][_sender].challenge == _challenge){ return true; } return false; }
12,753,769
[ 1, 2083, 2566, 635, 14881, 9005, 1491, 358, 866, 309, 326, 19170, 711, 10266, 1021, 1087, 9646, 460, 471, 501, 1297, 845, 471, 518, 1297, 506, 5242, 2353, 279, 2548, 3241, 326, 1142, 5107, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1954, 6492, 12, 2867, 389, 15330, 16, 2254, 389, 25092, 16, 2254, 389, 31993, 548, 13, 1071, 5381, 1135, 261, 6430, 389, 26810, 13, 288, 203, 3639, 309, 261, 31993, 863, 63, 67, 31993, 548, 6362, 67, 15330, 8009, 1132, 422, 4855, 9005, 1988, 1224, 863, 63, 67, 31993, 548, 6362, 67, 15330, 8009, 1132, 203, 3639, 597, 1203, 18, 5508, 411, 4855, 9005, 1988, 1224, 863, 63, 67, 31993, 548, 6362, 67, 15330, 8009, 5508, 203, 3639, 597, 19170, 863, 63, 67, 31993, 548, 6362, 67, 15330, 8009, 25092, 422, 389, 25092, 15329, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 3639, 327, 629, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6Ae49Cc128226BbEA767b8a91db6aeA9Ae3F1816/sources/contracts/BitstraySantasToken.sol
* @notice Mint a Bitstray Santa to provided address if project reserve is not 0, Used to distriute reserve @dev Call _mintTo with the to address(es)./
function mintTo(address to) public override returns (uint256) { require(totalSupply() < MAX_BITSTRAYSANTAS, "Mint would exceed max supply of Bitstray Santas"); require(remainingReserve() > 0, "Project reserved mint exceeded"); if (totalSupply() < MAX_BITSTRAYSANTAS) { reserveMinted++; return _mintTo(to, _currentBitstraySantaId++); } revert("Error: Your mint would exceed max supply of Bitstrays Santas"); }
9,792,337
[ 1, 49, 474, 279, 6539, 701, 528, 348, 27677, 358, 2112, 1758, 309, 1984, 20501, 353, 486, 374, 16, 10286, 358, 1015, 16857, 624, 20501, 225, 3049, 389, 81, 474, 774, 598, 326, 358, 1758, 12, 281, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 774, 12, 2867, 358, 13, 1071, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 411, 4552, 67, 15650, 882, 6722, 55, 6856, 3033, 16, 315, 49, 474, 4102, 9943, 943, 14467, 434, 6539, 701, 528, 348, 970, 345, 8863, 203, 3639, 2583, 12, 17956, 607, 6527, 1435, 405, 374, 16, 315, 4109, 8735, 312, 474, 12428, 8863, 203, 203, 3639, 309, 261, 4963, 3088, 1283, 1435, 411, 4552, 67, 15650, 882, 6722, 55, 6856, 3033, 13, 288, 203, 6647, 20501, 49, 474, 329, 9904, 31, 203, 6647, 327, 389, 81, 474, 774, 12, 869, 16, 389, 2972, 5775, 701, 528, 55, 27677, 548, 9904, 1769, 203, 3639, 289, 203, 3639, 15226, 2932, 668, 30, 20471, 312, 474, 4102, 9943, 943, 14467, 434, 6539, 701, 8271, 348, 970, 345, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Root file: contracts/cVToken.sol pragma solidity 0.6.12; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; contract cVToken is IERC20 { using SafeMath for uint256; uint256 constant private MAX_UINT256 = ~uint256(0); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name = "cVToken"; string private _symbol = "cV"; uint8 private _decimals = 18; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; constructor () public { _totalSupply = 9931143978000000000000000000; // https://etherscan.io/address/0xda6cb58a0d0c01610a29c5a65c303e13e885887c _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(_name)), keccak256(bytes('1')), chainId, address(this) ) ); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); if (_allowances[sender][msg.sender] < MAX_UINT256) { // treat MAX_UINT256 approve as infinite approval _approve(sender, msg.sender, _allowances[sender][msg.sender].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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "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 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"); _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 Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function transferMany(address[] calldata recipients, uint256[] calldata amounts) external { require(recipients.length == amounts.length, "cVToken: Wrong array length"); uint256 total = 0; for (uint256 i = 0; i < amounts.length; i++) { total = total.add(amounts[i]); } _balances[msg.sender] = _balances[msg.sender].sub(total, "ERC20: transfer amount exceeds balance"); for (uint256 i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint256 amount = amounts[i]; require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(msg.sender, recipient, amount); } } function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'cVToken: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'cVToken: INVALID_SIGNATURE'); _approve(owner, spender, value); } }
* @dev Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; }
10,971,844
[ 1, 3641, 6478, 7033, 3304, 326, 1699, 1359, 17578, 358, 1375, 87, 1302, 264, 68, 635, 326, 4894, 18, 1220, 353, 392, 10355, 358, 288, 12908, 537, 97, 716, 848, 506, 1399, 487, 279, 20310, 360, 367, 364, 9688, 11893, 316, 288, 45, 654, 39, 3462, 17, 12908, 537, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 29076, 30, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10929, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 3096, 620, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 389, 12908, 537, 12, 3576, 18, 15330, 16, 17571, 264, 16, 389, 5965, 6872, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 8009, 1289, 12, 9665, 620, 10019, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* When executed after the Kings contract, the entire token balance inside the contract will be transferred to the minter if they becomes the king which they are already the king. */ 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); } contract ERC918Interface { function epochCount() public constant returns (uint); function totalSupply() public constant returns (uint); function getMiningDifficulty() public constant returns (uint); function getMiningTarget() public constant returns (uint); function getMiningReward() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); } contract mintForwarderInterface { function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool success); } contract proxyMinterInterface { function proxyMint(uint256 nonce, bytes32 challenge_digest) public returns (bool success); } contract miningKingContract { function getKing() public returns (address king); } contract ownedContractInterface { address public owner; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract DoubleKingsReward is Owned { using SafeMath for uint; address public kingContract; address public minedToken; // 0xBTC is 0xb6ed7644c69416d67b522e20bc294a9a9b405b31; constructor(address mToken, address mkContract) public { minedToken = mToken; kingContract = mkContract; } function getBalance() view public returns (uint) { return ERC20Interface(minedToken).balanceOf(this); } //do not allow ether to enter function() public payable { revert(); } /** Pay out the token balance if the king becomes the king twice in a row **/ //proxyMintWithKing function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool) { require(proxyMintArray.length > 0); uint previousEpochCount = ERC918Interface(minedToken).epochCount(); address proxyMinter = proxyMintArray[0]; if(proxyMintArray.length == 1) { //Forward to the last proxyMint contract, typically a pool's owned mint contract require(proxyMinterInterface(proxyMinter).proxyMint(nonce, challenge_digest)); }else{ //if array length is greater than 1, pop the proxyMinter from the front of the array and keep cascading down the chain... address[] memory remainingProxyMintArray = popFirstFromArray(proxyMintArray); require(mintForwarderInterface(proxyMinter).mintForwarder(nonce, challenge_digest,remainingProxyMintArray)); } //make sure that the minedToken really was proxy minted through the proxyMint delegate call chain require( ERC918Interface(minedToken).epochCount() == previousEpochCount.add(1) ); // UNIQUE CONTRACT ACTION SPACE address proxyMinterAddress = ownedContractInterface(proxyMinter).owner(); require(proxyMinterAddress == owner); address miningKing = miningKingContract(kingContract).getKing(); bytes memory nonceBytes = uintToBytesForAddress(nonce); address newKing = bytesToAddress(nonceBytes); if(miningKing == newKing) { uint balance = ERC20Interface(minedToken).balanceOf(this); require(ERC20Interface(minedToken).transfer(newKing,balance)); } // -------- return true; } function popFirstFromArray(address[] array) pure public returns (address[] memory) { address[] memory newArray = new address[](array.length-1); for (uint i=0; i < array.length-1; i++) { newArray[i] = array[i+1] ; } return newArray; } function uintToBytesForAddress(uint256 x) pure public returns (bytes b) { b = new bytes(20); for (uint i = 0; i < 20; i++) { b[i] = byte(uint8(x / (2**(8*(31 - i))))); } return b; } function bytesToAddress (bytes b) pure public returns (address) { uint result = 0; for (uint i = b.length-1; i+1 > 0; i--) { uint c = uint(b[i]); uint to_inc = c * ( 16 ** ((b.length - i-1) * 2)); result += to_inc; } return address(result); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
0xBTC is 0xb6ed7644c69416d67b522e20bc294a9a9b405b31;
{ using SafeMath for uint; address public kingContract; address public minedToken; constructor(address mToken, address mkContract) public { minedToken = mToken; kingContract = mkContract; } function getBalance() view public returns (uint) { return ERC20Interface(minedToken).balanceOf(this); } function() public payable { revert(); } Pay out the token balance if the king becomes the king twice in a row function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool) { require(proxyMintArray.length > 0); uint previousEpochCount = ERC918Interface(minedToken).epochCount(); address proxyMinter = proxyMintArray[0]; if(proxyMintArray.length == 1) { require(proxyMinterInterface(proxyMinter).proxyMint(nonce, challenge_digest)); address[] memory remainingProxyMintArray = popFirstFromArray(proxyMintArray); require(mintForwarderInterface(proxyMinter).mintForwarder(nonce, challenge_digest,remainingProxyMintArray)); } require(proxyMinterAddress == owner); address miningKing = miningKingContract(kingContract).getKing(); bytes memory nonceBytes = uintToBytesForAddress(nonce); address newKing = bytesToAddress(nonceBytes); if(miningKing == newKing) { uint balance = ERC20Interface(minedToken).balanceOf(this); require(ERC20Interface(minedToken).transfer(newKing,balance)); } return true; } function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool) { require(proxyMintArray.length > 0); uint previousEpochCount = ERC918Interface(minedToken).epochCount(); address proxyMinter = proxyMintArray[0]; if(proxyMintArray.length == 1) { require(proxyMinterInterface(proxyMinter).proxyMint(nonce, challenge_digest)); address[] memory remainingProxyMintArray = popFirstFromArray(proxyMintArray); require(mintForwarderInterface(proxyMinter).mintForwarder(nonce, challenge_digest,remainingProxyMintArray)); } require(proxyMinterAddress == owner); address miningKing = miningKingContract(kingContract).getKing(); bytes memory nonceBytes = uintToBytesForAddress(nonce); address newKing = bytesToAddress(nonceBytes); if(miningKing == newKing) { uint balance = ERC20Interface(minedToken).balanceOf(this); require(ERC20Interface(minedToken).transfer(newKing,balance)); } return true; } }else{ require( ERC918Interface(minedToken).epochCount() == previousEpochCount.add(1) ); address proxyMinterAddress = ownedContractInterface(proxyMinter).owner(); function mintForwarder(uint256 nonce, bytes32 challenge_digest, address[] proxyMintArray) public returns (bool) { require(proxyMintArray.length > 0); uint previousEpochCount = ERC918Interface(minedToken).epochCount(); address proxyMinter = proxyMintArray[0]; if(proxyMintArray.length == 1) { require(proxyMinterInterface(proxyMinter).proxyMint(nonce, challenge_digest)); address[] memory remainingProxyMintArray = popFirstFromArray(proxyMintArray); require(mintForwarderInterface(proxyMinter).mintForwarder(nonce, challenge_digest,remainingProxyMintArray)); } require(proxyMinterAddress == owner); address miningKing = miningKingContract(kingContract).getKing(); bytes memory nonceBytes = uintToBytesForAddress(nonce); address newKing = bytesToAddress(nonceBytes); if(miningKing == newKing) { uint balance = ERC20Interface(minedToken).balanceOf(this); require(ERC20Interface(minedToken).transfer(newKing,balance)); } return true; } function popFirstFromArray(address[] array) pure public returns (address[] memory) { address[] memory newArray = new address[](array.length-1); for (uint i=0; i < array.length-1; i++) { newArray[i] = array[i+1] ; } return newArray; } function popFirstFromArray(address[] array) pure public returns (address[] memory) { address[] memory newArray = new address[](array.length-1); for (uint i=0; i < array.length-1; i++) { newArray[i] = array[i+1] ; } return newArray; } function uintToBytesForAddress(uint256 x) pure public returns (bytes b) { b = new bytes(20); for (uint i = 0; i < 20; i++) { b[i] = byte(uint8(x / (2**(8*(31 - i))))); } return b; } function uintToBytesForAddress(uint256 x) pure public returns (bytes b) { b = new bytes(20); for (uint i = 0; i < 20; i++) { b[i] = byte(uint8(x / (2**(8*(31 - i))))); } return b; } function bytesToAddress (bytes b) pure public returns (address) { uint result = 0; for (uint i = b.length-1; i+1 > 0; i--) { uint c = uint(b[i]); uint to_inc = c * ( 16 ** ((b.length - i-1) * 2)); result += to_inc; } return address(result); } function bytesToAddress (bytes b) pure public returns (address) { uint result = 0; for (uint i = b.length-1; i+1 > 0; i--) { uint c = uint(b[i]); uint to_inc = c * ( 16 ** ((b.length - i-1) * 2)); result += to_inc; } return address(result); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1,656,658
[ 1, 20, 20029, 15988, 353, 374, 6114, 26, 329, 27, 22087, 71, 8148, 24, 2313, 72, 9599, 70, 25, 3787, 73, 3462, 13459, 5540, 24, 69, 29, 69, 29, 70, 24, 6260, 70, 6938, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 203, 282, 1758, 1071, 417, 310, 8924, 31, 203, 203, 282, 1758, 1071, 1131, 329, 1345, 31, 203, 203, 203, 203, 225, 3885, 12, 2867, 312, 1345, 16, 1758, 5028, 8924, 13, 1071, 225, 288, 203, 565, 1131, 329, 1345, 273, 312, 1345, 31, 203, 565, 417, 310, 8924, 273, 5028, 8924, 31, 203, 225, 289, 203, 203, 203, 225, 445, 2882, 6112, 1435, 1476, 1071, 1135, 261, 11890, 13, 203, 225, 288, 203, 565, 327, 4232, 39, 3462, 1358, 12, 1154, 329, 1345, 2934, 12296, 951, 12, 2211, 1769, 203, 225, 289, 203, 203, 225, 445, 1435, 1071, 8843, 429, 288, 203, 1377, 15226, 5621, 203, 225, 289, 203, 203, 203, 203, 203, 203, 203, 13838, 596, 326, 1147, 11013, 309, 326, 417, 310, 12724, 326, 417, 310, 13605, 316, 279, 1027, 203, 203, 282, 445, 312, 474, 30839, 12, 11890, 5034, 7448, 16, 1731, 1578, 12948, 67, 10171, 16, 1758, 8526, 2889, 49, 474, 1076, 13, 1071, 1135, 261, 6430, 13, 203, 282, 288, 203, 203, 4202, 2583, 12, 5656, 49, 474, 1076, 18, 2469, 405, 374, 1769, 203, 203, 203, 4202, 2254, 2416, 14638, 1380, 273, 4232, 39, 29, 2643, 1358, 12, 1154, 329, 1345, 2934, 12015, 1380, 5621, 203, 203, 4202, 1758, 2889, 49, 2761, 273, 2889, 49, 474, 1076, 63, 20, 15533, 203, 203, 4202, 309, 12, 5656, 49, 474, 1076, 18, 2469, 422, 404, 13, 203, 4202, 288, 203, 540, 2583, 12, 5656, 49, 2761, 2 ]
./full_match/1/0x2C5e00ec69b27740CB8155736390ee7e74d279DB/sources/contracts/strategies/HStrategy.sol
@notice pulling missing tokens from erc20 vault on money and uniV3 vaults @param missingTokenAmounts the amount of missing tokens @param restrictions the restrictions of the amount of tokens to be transferred @param moneyVaultOptions additional parameters for pulling for `pull` method for money vault @param erc20Vault_ ERC20 vault of the strategy @param moneyVault_ Money vault of the strategy @param uniV3Vault_ UniswapV3 vault of the strategy @param tokens_ the addresses of the tokens managed by the strategy @return pulledToUniV3Vault the actual amount of tokens pulled into UniV3Vault
function _pullMissingTokens( TokenAmounts memory missingTokenAmounts, RebalanceTokenAmounts memory restrictions, bytes memory moneyVaultOptions, IIntegrationVault erc20Vault_, IIntegrationVault moneyVault_, IUniV3Vault uniV3Vault_, address[] memory tokens_ ) internal returns (uint256[] memory pulledToUniV3Vault) { pulledToUniV3Vault = new uint256[](2); uint256[] memory extraTokenAmountsForPull = new uint256[](2); { if (missingTokenAmounts.uniV3Token0 > 0 || missingTokenAmounts.uniV3Token1 > 0) { extraTokenAmountsForPull[0] = missingTokenAmounts.uniV3Token0; extraTokenAmountsForPull[1] = missingTokenAmounts.uniV3Token1; pulledToUniV3Vault = erc20Vault_.pull(address(uniV3Vault_), tokens_, extraTokenAmountsForPull, ""); _compareAmounts(restrictions.pulledToUniV3Vault, pulledToUniV3Vault); } } { if (missingTokenAmounts.moneyToken0 > 0 || missingTokenAmounts.moneyToken1 > 0) { extraTokenAmountsForPull[0] = missingTokenAmounts.moneyToken0; extraTokenAmountsForPull[1] = missingTokenAmounts.moneyToken1; erc20Vault_.pull(address(moneyVault_), tokens_, extraTokenAmountsForPull, moneyVaultOptions); } } }
16,590,861
[ 1, 13469, 310, 3315, 2430, 628, 6445, 71, 3462, 9229, 603, 15601, 471, 7738, 58, 23, 9229, 87, 225, 3315, 1345, 6275, 87, 326, 3844, 434, 3315, 2430, 225, 17499, 326, 17499, 434, 326, 3844, 434, 2430, 358, 506, 906, 4193, 225, 15601, 12003, 1320, 3312, 1472, 364, 6892, 310, 364, 1375, 13469, 68, 707, 364, 15601, 9229, 225, 6445, 71, 3462, 12003, 67, 4232, 39, 3462, 9229, 434, 326, 6252, 225, 15601, 12003, 67, 16892, 9229, 434, 326, 6252, 225, 7738, 58, 23, 12003, 67, 1351, 291, 91, 438, 58, 23, 9229, 434, 326, 6252, 225, 2430, 67, 326, 6138, 434, 326, 2430, 7016, 635, 326, 6252, 327, 30741, 774, 984, 77, 58, 23, 12003, 326, 3214, 3844, 434, 2430, 30741, 1368, 1351, 77, 58, 23, 12003, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13469, 4841, 5157, 12, 203, 3639, 3155, 6275, 87, 3778, 3315, 1345, 6275, 87, 16, 203, 3639, 868, 12296, 1345, 6275, 87, 3778, 17499, 16, 203, 3639, 1731, 3778, 15601, 12003, 1320, 16, 203, 3639, 467, 15372, 12003, 6445, 71, 3462, 12003, 67, 16, 203, 3639, 467, 15372, 12003, 15601, 12003, 67, 16, 203, 3639, 467, 984, 77, 58, 23, 12003, 7738, 58, 23, 12003, 67, 16, 203, 3639, 1758, 8526, 3778, 2430, 67, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 8526, 3778, 30741, 774, 984, 77, 58, 23, 12003, 13, 288, 203, 3639, 30741, 774, 984, 77, 58, 23, 12003, 273, 394, 2254, 5034, 8526, 12, 22, 1769, 203, 3639, 2254, 5034, 8526, 3778, 2870, 1345, 6275, 28388, 9629, 273, 394, 2254, 5034, 8526, 12, 22, 1769, 203, 3639, 288, 203, 5411, 309, 261, 7337, 1345, 6275, 87, 18, 318, 77, 58, 23, 1345, 20, 405, 374, 747, 3315, 1345, 6275, 87, 18, 318, 77, 58, 23, 1345, 21, 405, 374, 13, 288, 203, 7734, 2870, 1345, 6275, 28388, 9629, 63, 20, 65, 273, 3315, 1345, 6275, 87, 18, 318, 77, 58, 23, 1345, 20, 31, 203, 7734, 2870, 1345, 6275, 28388, 9629, 63, 21, 65, 273, 3315, 1345, 6275, 87, 18, 318, 77, 58, 23, 1345, 21, 31, 203, 7734, 30741, 774, 984, 77, 58, 23, 12003, 273, 6445, 71, 3462, 12003, 27799, 13469, 12, 2867, 12, 318, 77, 58, 23, 12003, 67, 3631, 2430, 67, 16, 2870, 1345, 6275, 28388, 9629, 16, 1408, 1769, 203, 7734, 389, 2 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** * @title AirSwap Server Registry * @notice Manage and query AirSwap server URLs */ contract Registry { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; event AddTokens(address account, address[] tokens); event RemoveTokens(address account, address[] tokens); event SetURL(address account, string url); IERC20 public immutable stakingToken; uint256 public immutable obligationCost; uint256 public immutable tokenCost; mapping(address => EnumerableSet.AddressSet) internal supportedTokens; mapping(address => EnumerableSet.AddressSet) internal supportingStakers; mapping(address => string) internal stakerURLs; /** * @notice Constructor * @param _stakingToken address of token used for staking * @param _obligationCost base amount required to stake * @param _tokenCost amount required to stake per token */ constructor( IERC20 _stakingToken, uint256 _obligationCost, uint256 _tokenCost ) { stakingToken = _stakingToken; obligationCost = _obligationCost; tokenCost = _tokenCost; } /** * @notice Set the URL for a staker * @param _url string value of the URL */ function setURL(string calldata _url) external { stakerURLs[msg.sender] = _url; emit SetURL(msg.sender, _url); } /** * @notice Return a list of all server URLs supporting a given token * @param token address of the token * @return urls array of server URLs supporting the token */ function getURLsForToken(address token) external view returns (string[] memory urls) { EnumerableSet.AddressSet storage stakers = supportingStakers[token]; uint256 length = stakers.length(); urls = new string[](length); for (uint256 i = 0; i < length; i++) { urls[i] = stakerURLs[address(stakers.at(i))]; } } /** * @notice Get the URLs for an array of stakers * @param stakers array of staker addresses * @return urls array of server URLs in the same order */ function getURLsForStakers(address[] calldata stakers) external view returns (string[] memory urls) { uint256 stakersLength = stakers.length; urls = new string[](stakersLength); for (uint256 i = 0; i < stakersLength; i++) { urls[i] = stakerURLs[stakers[i]]; } } /** * @notice Add tokens supported by the caller * @param tokens array of token addresses */ function addTokens(address[] calldata tokens) external { uint256 length = tokens.length; require(length > 0, "NO_TOKENS_TO_ADD"); EnumerableSet.AddressSet storage tokenList = supportedTokens[msg.sender]; uint256 transferAmount = 0; if (tokenList.length() == 0) { transferAmount = obligationCost; } for (uint256 i = 0; i < length; i++) { address token = tokens[i]; require(tokenList.add(token), "TOKEN_EXISTS"); supportingStakers[token].add(msg.sender); } transferAmount += tokenCost * length; emit AddTokens(msg.sender, tokens); stakingToken.safeTransferFrom(msg.sender, address(this), transferAmount); } /** * @notice Remove tokens supported by the caller * @param tokens array of token addresses */ function removeTokens(address[] calldata tokens) external { uint256 length = tokens.length; require(length > 0, "NO_TOKENS_TO_REMOVE"); EnumerableSet.AddressSet storage tokenList = supportedTokens[msg.sender]; for (uint256 i = 0; i < length; i++) { address token = tokens[i]; require(tokenList.remove(token), "TOKEN_DOES_NOT_EXIST"); supportingStakers[token].remove(msg.sender); } uint256 transferAmount = tokenCost * length; if (tokenList.length() == 0) { transferAmount += obligationCost; } emit RemoveTokens(msg.sender, tokens); stakingToken.safeTransfer(msg.sender, transferAmount); } /** * @notice Remove all tokens supported by the caller */ function removeAllTokens() external { EnumerableSet.AddressSet storage supportedTokenList = supportedTokens[msg.sender]; uint256 length = supportedTokenList.length(); require(length > 0, "NO_TOKENS_TO_REMOVE"); address[] memory tokenList = new address[](length); for (uint256 i = length; i > 0; ) { i--; address token = supportedTokenList.at(i); tokenList[i] = token; supportedTokenList.remove(token); supportingStakers[token].remove(msg.sender); } uint256 transferAmount = obligationCost + tokenCost * length; emit RemoveTokens(msg.sender, tokenList); stakingToken.safeTransfer(msg.sender, transferAmount); } /** * @notice Return whether a staker supports a given token * @param staker account address used to stake * @param token address of the token * @return true if the staker supports the token */ function supportsToken(address staker, address token) external view returns (bool) { return supportedTokens[staker].contains(token); } /** * @notice Return a list of all supported tokens for a given staker * @param staker account address of the staker * @return tokenList array of all the supported tokens */ function getSupportedTokens(address staker) external view returns (address[] memory tokenList) { EnumerableSet.AddressSet storage tokens = supportedTokens[staker]; uint256 length = tokens.length(); tokenList = new address[](length); for (uint256 i = 0; i < length; i++) { tokenList[i] = tokens.at(i); } } /** * @notice Return a list of all stakers supporting a given token * @param token address of the token * @return stakers array of all stakers that support a given token */ function getStakersForToken(address token) external view returns (address[] memory stakers) { EnumerableSet.AddressSet storage stakerList = supportingStakers[token]; uint256 length = stakerList.length(); stakers = new address[](length); for (uint256 i = 0; i < length; i++) { stakers[i] = stakerList.at(i); } } /** * @notice Return the staking balance of a given staker * @param staker address of the account used to stake * @return balance of the staker account */ function balanceOf(address staker) external view returns (uint256) { uint256 tokenCount = supportedTokens[staker].length(); if (tokenCount == 0) { return 0; } return obligationCost + tokenCost * tokenCount; } } // 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 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] = 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) { 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.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); } } } }
* @notice Remove all tokens supported by the caller/
function removeAllTokens() external { EnumerableSet.AddressSet storage supportedTokenList = supportedTokens[msg.sender]; uint256 length = supportedTokenList.length(); require(length > 0, "NO_TOKENS_TO_REMOVE"); address[] memory tokenList = new address[](length); for (uint256 i = length; i > 0; ) { i--; address token = supportedTokenList.at(i); tokenList[i] = token; supportedTokenList.remove(token); supportingStakers[token].remove(msg.sender); } uint256 transferAmount = obligationCost + tokenCost * length; emit RemoveTokens(msg.sender, tokenList); stakingToken.safeTransfer(msg.sender, transferAmount); }
12,070,906
[ 1, 3288, 777, 2430, 3260, 635, 326, 4894, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 12787, 5157, 1435, 3903, 288, 203, 565, 6057, 25121, 694, 18, 1887, 694, 2502, 3260, 1345, 682, 273, 203, 1377, 3260, 5157, 63, 3576, 18, 15330, 15533, 203, 565, 2254, 5034, 769, 273, 3260, 1345, 682, 18, 2469, 5621, 203, 565, 2583, 12, 2469, 405, 374, 16, 315, 3417, 67, 8412, 55, 67, 4296, 67, 22122, 8863, 203, 565, 1758, 8526, 3778, 1147, 682, 273, 394, 1758, 8526, 12, 2469, 1769, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 769, 31, 277, 405, 374, 31, 262, 288, 203, 1377, 277, 413, 31, 203, 1377, 1758, 1147, 273, 3260, 1345, 682, 18, 270, 12, 77, 1769, 203, 1377, 1147, 682, 63, 77, 65, 273, 1147, 31, 203, 1377, 3260, 1345, 682, 18, 4479, 12, 2316, 1769, 203, 1377, 22930, 510, 581, 414, 63, 2316, 8009, 4479, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 565, 2254, 5034, 7412, 6275, 273, 320, 31627, 367, 8018, 397, 1147, 8018, 380, 769, 31, 203, 565, 3626, 3581, 5157, 12, 3576, 18, 15330, 16, 1147, 682, 1769, 203, 565, 384, 6159, 1345, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 7412, 6275, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IERC20 { function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); } interface IMasterChef { function userInfo(uint256 nr, address who) external view returns (uint256, uint256); function pending(uint256 nr, address who) external view returns (uint256); } interface BalancerVault { function getPoolTokenInfo(bytes32, address) external view returns (uint256, uint256, uint256, address); function getPool(bytes32) external view returns (address, uint8); } contract QIPOWAHFTM { using SafeMath for uint256; BalancerVault vault = BalancerVault(0x20dd72Ed959b6147912C2e529F0a0C651c33c9ce); function name() public pure returns(string memory) { return "QIPOWAHFTM"; } function symbol() public pure returns(string memory) { return "QIPOWAHFTM"; } function decimals() public pure returns(uint8) { return 18; } function totalSupply() public view returns (uint256) { IERC20 qi = IERC20(0x68Aa691a8819B07988B18923F712F3f4C8d36346);// qidao erc20 uint256 qi_totalQi = qi.totalSupply().mul(4); /// x 4 because boost in eQi return qi_totalQi;//lp_totalQi.add(qi_totalQi); } function calculateBalancerPoolTokenSupply(bytes32 poolId, IERC20 token) public view returns (uint256){ (uint256 poolTokenBalance, , , ) = vault.getPoolTokenInfo(poolId, address(token)); return poolTokenBalance; } function balanceOf(address owner) public view returns (uint256) { IMasterChef chef = IMasterChef(0x230917f8a262bF9f2C3959eC495b11D1B7E1aFfC); // rewards/staking contract IERC20 beetsPair = IERC20(0x7aE6A223cde3A17E0B95626ef71A2DB5F03F540A); //Qi-miMatic beets pair bytes32 beetsPoolId = 0x7ae6a223cde3a17e0b95626ef71a2db5f03f540a00020000000000000000008a; IERC20 qi = IERC20(0x68Aa691a8819B07988B18923F712F3f4C8d36346);// qidao erc20 // Get Qi balance of user on Fantom uint256 qi_powah = qi.balanceOf(owner); // Total Qi held in beets pair uint256 lp_totalQi = calculateBalancerPoolTokenSupply(beetsPoolId, qi); // Beets pair tokens held by owner uint256 lp_balance = beetsPair.balanceOf(owner); // Get staked balance of owner (uint256 lp_stakedBalanceOne, ) = chef.userInfo(1, owner); //Qi-WFTM Farmed Bal lp_balance = lp_balance.add(lp_stakedBalanceOne); uint256 lp_powah = 0; if (lp_balance > 0) { // QI Balance of the beets pair * (the staked + non staked LP balance of the owner) / all the lp tokens for the pair lp_powah = lp_totalQi.mul(lp_balance).div(beetsPair.totalSupply()); } qi_powah = qi_powah.add(chef.pending(0, owner)); // Unclaimed reward Qi from USDC-miMatic qi_powah = qi_powah.add(chef.pending(1, owner)); // Unclaimed reward Qi from WFTM-Qi // Add and return staked QI return lp_powah.add(qi_powah); } function allowance(address, address) public pure returns (uint256) { return 0; } function transfer(address, uint256) public pure returns (bool) { return false; } function approve(address, uint256) public pure returns (bool) { return false; } function transferFrom(address, address, uint256) public pure returns (bool) { return false; } }
Unclaimed reward Qi from WFTM-Qi
qi_powah = qi_powah.add(chef.pending(1, owner));
15,801,042
[ 1, 984, 14784, 329, 19890, 2238, 77, 628, 678, 4464, 49, 17, 53, 77, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1043, 77, 67, 23509, 9795, 273, 1043, 77, 67, 23509, 9795, 18, 1289, 12, 343, 10241, 18, 9561, 12, 21, 16, 3410, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x30b3EaB9450036C432C1D2529E031D0F340E154e/sources/contracts/ASICLottery.sol
mapping that store winners addresses for each game
mapping(uint256 => DrawResult) public drawHistory;
4,938,281
[ 1, 6770, 716, 1707, 5657, 9646, 6138, 364, 1517, 7920, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 10184, 1253, 13, 1071, 3724, 5623, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; import "./DragonBase.sol"; import "../Common/SafeMath16.sol"; /* solium-disable operator-whitespace */ contract DragonCore is DragonBase { using SafeMath16 for uint16; uint8 constant MAX_LEVEL = 10; // max dragon level uint8 constant MAX_TACTICS_PERCENTAGE = 80; uint8 constant MIN_TACTICS_PERCENTAGE = 20; uint8 constant MAX_GENE_LVL = 99; // max dragon gene level uint8 constant NUMBER_OF_SPECIAL_PEACEFUL_SKILL_CLASSES = 8; // first is empty skill // does dragon have enough DNA points for breeding? function isBreedingAllowed(uint8 _level, uint16 _dnaPoints) public view returns (bool) { return _level > 0 && _dnaPoints >= params.dnaPoints(_level); } function _checkIfEnoughPoints(bool _isEnough) internal pure { require(_isEnough, "not enough points"); } function _validateSpecialPeacefulSkillClass(uint8 _class) internal pure { require(_class > 0 && _class < NUMBER_OF_SPECIAL_PEACEFUL_SKILL_CLASSES, "wrong class of special peaceful skill"); } function _checkIfSpecialPeacefulSkillAvailable(bool _isAvailable) internal pure { require(_isAvailable, "special peaceful skill selection is not available"); } function _getBuff(uint256 _id, uint8 _class) internal view returns (uint32) { return _storage_.buffs(_id, _class); } function _getAllBuffs(uint256 _id) internal view returns (uint32[5]) { return [ _getBuff(_id, 1), _getBuff(_id, 2), _getBuff(_id, 3), _getBuff(_id, 4), _getBuff(_id, 5) ]; } // GETTERS function calculateMaxHealthAndManaWithBuffs(uint256 _id) public view returns ( uint32 maxHealth, uint32 maxMana ) { (, , uint32 _stamina, , uint32 _intelligence) = _storage_.skills(_id); ( maxHealth, maxMana ) = helper.calculateHealthAndMana( _stamina, _intelligence, _getBuff(_id, 3), // stamina buff _getBuff(_id, 5) // intelligence buff ); } function getCurrentHealthAndMana(uint256 _id) public view returns ( uint32 health, uint32 mana, uint8 healthPercentage, uint8 manaPercentage ) { ( uint256 _timestamp, uint32 _remainingHealth, uint32 _remainingMana, uint32 _maxHealth, uint32 _maxMana ) = _storage_.healthAndMana(_id); (_maxHealth, _maxMana) = calculateMaxHealthAndManaWithBuffs(_id); uint256 _pastTime = now.sub(_timestamp); // solium-disable-line security/no-block-members (health, healthPercentage) = helper.calculateCurrent(_pastTime, _maxHealth, _remainingHealth); (mana, manaPercentage) = helper.calculateCurrent(_pastTime, _maxMana, _remainingMana); } // SETTERS function setRemainingHealthAndMana( uint256 _id, uint32 _remainingHealth, uint32 _remainingMana ) external onlyController { _storage_.setRemainingHealthAndMana(_id, _remainingHealth, _remainingMana); } function increaseExperience(uint256 _id, uint256 _factor) external onlyController { ( uint8 _level, uint256 _experience, uint16 _dnaPoints ) = _storage_.levels(_id); uint8 _currentLevel = _level; if (_level < MAX_LEVEL) { (_level, _experience, _dnaPoints) = helper.calculateExperience(_level, _experience, _dnaPoints, _factor); if (_level > _currentLevel) { // restore hp and mana if level up _storage_.resetHealthAndManaTimestamp(_id); } if (_level == MAX_LEVEL) { _experience = 0; } _storage_.setLevel(_id, _level, _experience.toUint8(), _dnaPoints); } } function payDNAPointsForBreeding(uint256 _id) external onlyController { ( uint8 _level, uint8 _experience, uint16 _dnaPoints ) = _storage_.levels(_id); _checkIfEnoughPoints(isBreedingAllowed(_level, _dnaPoints)); _dnaPoints = _dnaPoints.sub(params.dnaPoints(_level)); _storage_.setLevel(_id, _level, _experience, _dnaPoints); } function upgradeGenes(uint256 _id, uint16[10] _dnaPoints) external onlyController { ( uint8 _level, uint8 _experience, uint16 _availableDNAPoints ) = _storage_.levels(_id); uint16 _sum; uint256[4] memory _newComposedGenome; ( _newComposedGenome, _sum ) = helper.upgradeGenes( _storage_.getGenome(_id), _dnaPoints, _availableDNAPoints ); require(_sum > 0, "DNA points were not used"); _availableDNAPoints = _availableDNAPoints.sub(_sum); // save data _storage_.setLevel(_id, _level, _experience, _availableDNAPoints); _storage_.setGenome(_id, _newComposedGenome); _storage_.setCoolness(_id, helper.calculateCoolness(_newComposedGenome)); // recalculate skills _saveSkills(_id, _newComposedGenome); } function _saveSkills(uint256 _id, uint256[4] _genome) internal { ( uint32 _attack, uint32 _defense, uint32 _stamina, uint32 _speed, uint32 _intelligence ) = helper.calculateSkills(_genome); ( uint32 _health, uint32 _mana ) = helper.calculateHealthAndMana(_stamina, _intelligence, 0, 0); // without buffs _storage_.setMaxHealthAndMana(_id, _health, _mana); _storage_.setSkills(_id, _attack, _defense, _stamina, _speed, _intelligence); } function increaseWins(uint256 _id) external onlyController { (uint16 _wins, ) = _storage_.battles(_id); _storage_.setWins(_id, _wins.add(1)); } function increaseDefeats(uint256 _id) external onlyController { (, uint16 _defeats) = _storage_.battles(_id); _storage_.setDefeats(_id, _defeats.add(1)); } function setTactics(uint256 _id, uint8 _melee, uint8 _attack) external onlyController { require( _melee >= MIN_TACTICS_PERCENTAGE && _melee <= MAX_TACTICS_PERCENTAGE && _attack >= MIN_TACTICS_PERCENTAGE && _attack <= MAX_TACTICS_PERCENTAGE, "tactics value must be between 20 and 80" ); _storage_.setTactics(_id, _melee, _attack); } function calculateSpecialPeacefulSkill(uint256 _id) public view returns ( uint8 class, uint32 cost, uint32 effect ) { class = _storage_.specialPeacefulSkills(_id); if (class == 0) return; ( uint32 _attack, uint32 _defense, uint32 _stamina, uint32 _speed, uint32 _intelligence ) = _storage_.skills(_id); ( cost, effect ) = helper.calculateSpecialPeacefulSkill( class, [_attack, _defense, _stamina, _speed, _intelligence], _getAllBuffs(_id) ); } function setSpecialPeacefulSkill(uint256 _id, uint8 _class) external onlyController { (uint8 _level, , ) = _storage_.levels(_id); uint8 _currentClass = _storage_.specialPeacefulSkills(_id); _checkIfSpecialPeacefulSkillAvailable(_level == MAX_LEVEL); _validateSpecialPeacefulSkillClass(_class); _checkIfSpecialPeacefulSkillAvailable(_currentClass == 0); _storage_.setSpecialPeacefulSkill(_id, _class); } function _getBuffIndexBySpecialPeacefulSkillClass( uint8 _class ) internal pure returns (uint8) { uint8[8] memory _buffsIndexes = [0, 1, 2, 3, 4, 5, 3, 5]; // 0 item - no such class return _buffsIndexes[_class]; } // _id - dragon, which will use the skill // _target - dragon, on which the skill will be used // _sender - owner of the first dragon function useSpecialPeacefulSkill(address _sender, uint256 _id, uint256 _target) external onlyController { ( uint8 _class, uint32 _cost, uint32 _effect ) = calculateSpecialPeacefulSkill(_id); ( uint32 _health, uint32 _mana, , ) = getCurrentHealthAndMana(_id); _validateSpecialPeacefulSkillClass(_class); // enough mana _checkIfEnoughPoints(_mana >= _cost); // subtract cost of special peaceful skill _storage_.setRemainingHealthAndMana(_id, _health, _mana.sub(_cost)); // reset intelligence buff of the first dragon _storage_.setBuff(_id, 5, 0); // reset active skill buff of the first dragon uint8 _buffIndexOfActiveSkill = _getBuffIndexBySpecialPeacefulSkillClass(_class); _storage_.setBuff(_id, _buffIndexOfActiveSkill, 0); if (_class == 6 || _class == 7) { // health/mana restoration ( uint32 _targetHealth, uint32 _targetMana, , ) = getCurrentHealthAndMana(_target); if (_class == 6) _targetHealth = _targetHealth.add(_effect); // restore health if (_class == 7) _targetMana = _targetMana.add(_effect); // restore mana // save restored health/mana _storage_.setRemainingHealthAndMana( _target, _targetHealth, _targetMana ); } else { // another special peaceful skills if (_storage_.ownerOf(_target) != _sender) { // to prevert lower effect buffing require(_getBuff(_target, _class) < _effect, "you can't buff alien dragon by lower effect"); } _storage_.setBuff(_target, _class, _effect); } } function setBuff(uint256 _id, uint8 _class, uint32 _effect) external onlyController { _storage_.setBuff(_id, _class, _effect); } function createDragon( address _sender, uint16 _generation, uint256[2] _parents, uint256[4] _genome, uint8[11] _dragonTypes ) external onlyController returns (uint256 newDragonId) { newDragonId = _storage_.push(_sender, _generation, _genome, _parents, _dragonTypes); uint32 _coolness = helper.calculateCoolness(_genome); _storage_.setCoolness(newDragonId, _coolness); _storage_.setTactics(newDragonId, 50, 50); _setSkillsAndHealthAndMana(newDragonId, _genome, _dragonTypes); } function setName( uint256 _id, string _name ) external onlyController returns (bytes32) { ( bytes32 _initial, // initial name that converted to bytes32 bytes32 _lowercase // name to lowercase ) = helper.checkAndConvertName(_name); require(!_storage_.existingNames(_lowercase), "name exists"); require(_storage_.names(_id) == 0x0, "dragon already has a name"); _storage_.setName(_id, _initial, _lowercase); return _initial; } }
_id - dragon, which will use the skill _target - dragon, on which the skill will be used _sender - owner of the first dragon enough mana subtract cost of special peaceful skill reset intelligence buff of the first dragon reset active skill buff of the first dragon save restored health/mana
function useSpecialPeacefulSkill(address _sender, uint256 _id, uint256 _target) external onlyController { ( uint8 _class, uint32 _cost, uint32 _effect ) = calculateSpecialPeacefulSkill(_id); ( uint32 _health, uint32 _mana, , ) = getCurrentHealthAndMana(_id); _validateSpecialPeacefulSkillClass(_class); _checkIfEnoughPoints(_mana >= _cost); _storage_.setRemainingHealthAndMana(_id, _health, _mana.sub(_cost)); _storage_.setBuff(_id, 5, 0); uint8 _buffIndexOfActiveSkill = _getBuffIndexBySpecialPeacefulSkillClass(_class); _storage_.setBuff(_id, _buffIndexOfActiveSkill, 0); ( uint32 _targetHealth, uint32 _targetMana, , ) = getCurrentHealthAndMana(_target); _storage_.setRemainingHealthAndMana( _target, _targetHealth, _targetMana ); require(_getBuff(_target, _class) < _effect, "you can't buff alien dragon by lower effect"); } _storage_.setBuff(_target, _class, _effect);
953,543
[ 1, 67, 350, 300, 8823, 265, 16, 1492, 903, 999, 326, 15667, 389, 3299, 300, 8823, 265, 16, 603, 1492, 326, 15667, 903, 506, 1399, 389, 15330, 300, 3410, 434, 326, 1122, 8823, 265, 7304, 3161, 69, 10418, 6991, 434, 4582, 2804, 623, 2706, 15667, 2715, 509, 1165, 360, 802, 6139, 434, 326, 1122, 8823, 265, 2715, 2695, 15667, 6139, 434, 326, 1122, 8823, 265, 1923, 18751, 8437, 19, 4728, 69, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 999, 12193, 11227, 623, 2706, 9030, 12, 2867, 389, 15330, 16, 2254, 5034, 389, 350, 16, 2254, 5034, 389, 3299, 13, 3903, 1338, 2933, 288, 203, 3639, 261, 203, 5411, 2254, 28, 389, 1106, 16, 203, 5411, 2254, 1578, 389, 12398, 16, 203, 5411, 2254, 1578, 389, 13867, 203, 3639, 262, 273, 4604, 12193, 11227, 623, 2706, 9030, 24899, 350, 1769, 203, 3639, 261, 203, 5411, 2254, 1578, 389, 13267, 16, 203, 5411, 2254, 1578, 389, 4728, 69, 16, 269, 203, 3639, 262, 273, 5175, 7802, 1876, 5669, 69, 24899, 350, 1769, 203, 203, 3639, 389, 5662, 12193, 11227, 623, 2706, 9030, 797, 24899, 1106, 1769, 203, 3639, 389, 1893, 2047, 664, 4966, 5636, 24899, 4728, 69, 1545, 389, 12398, 1769, 203, 203, 3639, 389, 5697, 27799, 542, 11429, 7802, 1876, 5669, 69, 24899, 350, 16, 389, 13267, 16, 389, 4728, 69, 18, 1717, 24899, 12398, 10019, 203, 3639, 389, 5697, 27799, 542, 10642, 24899, 350, 16, 1381, 16, 374, 1769, 203, 3639, 2254, 28, 389, 20664, 31985, 3896, 9030, 273, 389, 588, 10642, 1016, 858, 12193, 11227, 623, 2706, 9030, 797, 24899, 1106, 1769, 203, 3639, 389, 5697, 27799, 542, 10642, 24899, 350, 16, 389, 20664, 31985, 3896, 9030, 16, 374, 1769, 203, 203, 5411, 261, 203, 7734, 2254, 1578, 389, 3299, 7802, 16, 203, 7734, 2254, 1578, 389, 3299, 5669, 69, 16, 269, 203, 5411, 262, 273, 5175, 7802, 1876, 5669, 69, 24899, 3299, 1769, 203, 5411, 389, 5697, 27799, 542, 11429, 7802, 1876, 5669, 69, 12, 203, 7734, 389, 2 ]
./full_match/137/0x0767c06D06040929fB81DEF2065697a054Ee39FF/sources/contracts/Contract.sol
Record exact amount
addToBlockchain(recipient, amount, message);
3,768,552
[ 1, 2115, 5565, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9604, 1768, 5639, 12, 20367, 16, 3844, 16, 883, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x773625e0BAd43271d8d5F7483E2f3dAF3712c37e/sources/DigitalNFT.sol
* @dev Mints a new NFT. @param _to The address that will own the minted NFT./check EIP712 signature from artist that validates the [ uri , artist, and KeypassToken ]
function mint( address _to, address artist, address keypassToken, string memory uri, uint256 maxCopies, uint256 expirationBlock, address currencyToken, uint256 currencyAmount, bytes memory signature) external returns(bool) { bytes32 sigHash = getTypedDataHash(artist,keypassToken, uri, maxCopies, expirationBlock, currencyToken, currencyAmount); address recoveredSignatureSigner = recover(sigHash,signature); require(artist == recoveredSignatureSigner, 'Invalid signature'); require(expirationBlock == 0 || block.number < expirationBlock, 'Packet has expired.'); if(keypassToken != address(0x0)){ require( ERC721(keypassToken).balanceOf(_to) >= 1 ); } if(currencyToken != address(0x0)){ _transferCurrencyForSale(_to, artist, currencyToken , currencyAmount ); } uint256 projectId = uint256( sigHash ); super._mint(_to,tokensMinted); super._setTokenProjectId(tokensMinted,projectId ); if(numberOfCopies[projectId] == 0){ super._setProjectArtist(projectId, artist); super._setProjectUri(projectId, uri); require(projectUriBurned[keccak256(bytes(uri))] == false, 'project uri already burned'); projectUriBurned[keccak256(bytes(uri))] = true; } require(numberOfCopies[projectId] < maxCopies, "exceeded max copies"); numberOfCopies[projectId] = numberOfCopies[projectId]+1; tokensMinted = tokensMinted + 1; return true; }
1,857,237
[ 1, 49, 28142, 279, 394, 423, 4464, 18, 225, 389, 869, 1021, 1758, 716, 903, 4953, 326, 312, 474, 329, 423, 4464, 18, 19, 1893, 512, 2579, 27, 2138, 3372, 628, 15469, 716, 11964, 326, 306, 2003, 225, 269, 15469, 16, 471, 1929, 5466, 1345, 225, 308, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 12, 1758, 389, 869, 16, 1758, 15469, 16, 1758, 498, 5466, 1345, 16, 533, 3778, 2003, 16, 2254, 5034, 943, 15670, 16, 2254, 5034, 7686, 1768, 16, 1758, 5462, 1345, 16, 2254, 5034, 5462, 6275, 16, 1731, 3778, 3372, 13, 3903, 1135, 12, 6430, 13, 288, 21281, 377, 203, 565, 1731, 1578, 3553, 2310, 273, 3181, 6140, 751, 2310, 12, 25737, 16, 856, 5466, 1345, 16, 2003, 16, 943, 15670, 16, 7686, 1768, 16, 5462, 1345, 16, 5462, 6275, 1769, 203, 565, 1758, 24616, 5374, 15647, 273, 5910, 12, 7340, 2310, 16, 8195, 1769, 203, 565, 2583, 12, 25737, 422, 24616, 5374, 15647, 16, 296, 1941, 3372, 8284, 7010, 377, 203, 565, 2583, 12, 19519, 1768, 422, 374, 747, 1203, 18, 2696, 411, 7686, 1768, 16, 296, 6667, 711, 7708, 1093, 1769, 203, 7010, 565, 309, 12, 856, 5466, 1345, 480, 1758, 12, 20, 92, 20, 3719, 95, 203, 3639, 2583, 12, 4232, 39, 27, 5340, 12, 856, 5466, 1345, 2934, 12296, 951, 24899, 869, 13, 1545, 404, 11272, 7010, 565, 289, 7010, 377, 203, 565, 309, 12, 7095, 1345, 480, 1758, 12, 20, 92, 20, 3719, 95, 7010, 3639, 389, 13866, 7623, 1290, 30746, 24899, 869, 16, 15469, 16, 5462, 1345, 269, 5462, 6275, 11272, 203, 565, 289, 7010, 377, 203, 377, 203, 565, 2254, 5034, 9882, 273, 2254, 5034, 12, 3553, 2310, 11272, 203, 377, 203, 1377, 203, 565, 2240, 6315, 81, 474, 24899, 869, 16, 7860, 49, 474, 329, 1769, 7010, 565, 2240, 6315, 542, 1345, 4109, 2 ]
/** * @authors: [@unknownunknown1] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [] */ /* solium-disable security/no-block-members */ pragma solidity ^0.5.0; import "./KlerosLiquid.sol"; import "@kleros/kleros-interaction/contracts/libraries/CappedMath.sol"; contract KlerosGovernor is Arbitrable{ using CappedMath for uint; /* *** Contract variables *** */ uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. enum Status {NoDispute, DisputeCreated} struct Transaction{ uint ID; // Hash of the transaction converted into uint. Is needed for sorting transactions in a list. address target; // The address that will execute the transaction. uint value; // Value paid by submitter that will be used as msg.value in the execution. bytes data; // Calldata of the transaction. bool executed; // Whether the transaction was already executed or not. Is needed to prevent re-entrancy. } struct TransactionList{ address sender; // Submitter's address. uint deposit; // Value of a deposit paid upon submission of the list. mapping(uint => Transaction) transactions; // Transactions stored in the list. bytes32 listHash; // A hash chain of all transactions stored in the list. Is needed to catch duplicates. uint submissionTime; // Time the list was submitted. mapping(uint => bool) appealFeePaid; // Whether the appeal fee for the list has been paid in certain round. uint txCounter; // Number of stored transactions. } Status public status; // Status showing whether the contract has an ongoing dispute or not. uint public submissionDeposit; // Value in wei that needs to be paid in order to submit the list. uint public submissionTimeout; // Time in seconds allowed for submitting the lists. Once it's passed the contract enters the execution period which will end when the transaction list is executed. uint public withdrawTimeout; // Time in seconds allowed to withdraw a submitted list. uint public sumDeposit; // Sum of all submission deposits in a session. Is needed for calculating a reward. uint public lastAction; // The time of the last execution of a transaction list. uint public disputeID; // The ID of the dispute created in Kleros court. uint public round; // Current round of the dispute. 0 - dispute round, 1 and more - appeal rounds. mapping (uint => uint) public submissions; // Gives an index to a submitted list and maps it with respective index in array of transactions. Is needed to separate all created lists from the ones submitted in the current session. mapping(uint => uint) public submissionCounter; // Maps the round to the number of submissions made in it. For the appeal rounds submission is counted as payment for appeal fees. uint public sharedStakeMultiplier; // Multiplier for calculating the appeal fee that must be paid by submitter in the case where there isn't a winner and loser (e.g. when the arbitrator ruled "refused to rule"/"could not rule"). uint public winnerStakeMultiplier; // Multiplier for calculating the appeal fee of the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the appeal fee of the party that lost the previous round. TransactionList[] public txLists; // Stores all created transaction lists. /* *** Modifiers *** */ modifier depositRequired() {require(msg.value >= submissionDeposit, "Submission deposit must be paid"); _;} modifier duringSubmissionPeriod() {require(now <= lastAction + submissionTimeout, "Submission time has ended"); _;} modifier duringExecutionPeriod() {require(now > lastAction + submissionTimeout, "Execution time has not started yet"); _;} /** @dev Constructor. * @param _kleros The arbitrator of the contract. * @param _extraData Extra data for the arbitrator. * @param _submissionDeposit The deposit required for list submission. * @param _submissionTimeout Time in seconds allocated for submitting transaction list. * @param _withdrawTimeout Time in seconds after submission that allows to withdraw submitted list. * @param _sharedStakeMultiplier Multiplier of the appeal cost that submitter must pay for a round when there isn't a winner/loser in the previous round. In basis points. * @param _winnerStakeMultiplier Multiplier of the appeal cost that the winner has to pay for a round. In basis points. * @param _loserStakeMultiplier Multiplier of the appeal cost that the loser has to pay for a round. In basis points. */ constructor( KlerosLiquid _kleros, bytes _extraData, uint _submissionDeposit, uint _submissionTimeout, uint _withdrawTimeout, uint _winnerStakeMultiplier, uint _loserStakeMultiplier, uint _sharedStakeMultiplier )public Arbitrable(_kleros, _extraData){ lastAction = now; submissionDeposit = _submissionDeposit; submissionTimeout = _submissionTimeout; withdrawTimeout = _withdrawTimeout; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Creates an empty transaction list. * @return listID The array index of the created list. */ function createTransactionList() public duringSubmissionPeriod returns(uint listID){ txLists.length++; listID = txLists.length - 1; TransactionList storage txList = txLists[listID]; txList.sender = msg.sender; } /** @dev Adds a transaction to created list. Sorts added transactions by ID in the process. * @param _listID The index of the transaction list in the array of lists. * @param _target The target of the transaction. * @param _data The calldata of the transaction. */ function addTransactions(uint _listID, address _target, bytes _data) public payable duringSubmissionPeriod { TransactionList storage txList = txLists[_listID]; require(txList.sender == msg.sender, "Can't add transactions to the list created by someone else"); require(txList.submissionTime == 0, "List is already submitted"); txList.txCounter++; uint ID = uint(keccak256(abi.encodePacked(_target, msg.value, _data))); uint index; bool found; // Transactions are sorted to catch lists with the same transactions that were added in different order. if (txList.txCounter > 1) { for (uint i = txList.txCounter - 2; i >= 0; i--){ if (ID < txList.transactions[i].ID){ Transaction storage currentTx = txList.transactions[i]; txList.transactions[i + 1] = currentTx; delete txList.transactions[i]; index = i; found = true; } else { break; } } } if (!found) index = txList.txCounter - 1; Transaction storage transaction = txList.transactions[index]; transaction.ID = ID; transaction.target = _target; transaction.value = msg.value; transaction.data = _data; } /** @dev Submits created transaction list so it can be executed in the execution period. * @param _listID The index of the transaction list in the array of lists. */ function submitTransactionList(uint _listID) public payable depositRequired duringSubmissionPeriod{ TransactionList storage txList = txLists[_listID]; require(txList.sender == msg.sender, "Can't submit the list created by someone else"); require(txList.submissionTime == 0, "List is already submitted"); txList.submissionTime = now; txList.deposit = submissionDeposit; // Stores the hash of the list to catch duplicates. if (txList.txCounter > 0){ bytes32 listHash = bytes32(txList.transactions[0].ID); for (uint i = 1; i < txList.txCounter; i++){ listHash = keccak256(abi.encodePacked(bytes32(txList.transactions[i].ID), listHash)); } txList.listHash = listHash; } sumDeposit += submissionDeposit; submissionCounter[round]++; submissions[submissionCounter[round]] = _listID; uint surplus = msg.value - submissionDeposit; if (surplus > 0) msg.sender.send(surplus); } /** @dev Withdraws submitted transaction list. Reimburses submission deposit. * @param _submissionID The ID that was given to the list upon submission. For a newly submitted list its submission ID is equal to the total submission count. */ function withdrawTransactionList(uint _submissionID) public duringSubmissionPeriod{ require(_submissionID > 0 && _submissionID <= submissionCounter[0], "ID is out of range"); TransactionList storage txList = txLists[submissions[_submissionID]]; require(txList.sender == msg.sender, "Can't withdraw the list created by someone else"); require(now - txList.submissionTime <= withdrawTimeout, "Withdrawing time has passed"); uint deposit = txList.deposit; // Replace the ID of the withdrawn list with the last submitted list to close the gap. submissions[_submissionID] = submissions[submissionCounter[0]]; delete submissions[submissionCounter[0]]; submissionCounter[0]--; sumDeposit -= deposit; require(msg.sender.send(deposit), "Was unable to return deposit"); } /** @dev Executes a transaction list or creates a dispute if more than one list was submitted. If nothing was submitted resets the period of the contract to the submission period. * Note that the choices of created dispute mirror submission IDs of submitted lists. */ function executeTransactionList() public duringExecutionPeriod{ require(status == Status.NoDispute, "Can't execute transaction list while dispute is active"); if (submissionCounter[round] == 0){ lastAction = now; return; } if (submissionCounter[round] == 1) { TransactionList storage txList = txLists[submissions[1]]; for (uint i = 0; i < txList.txCounter; i++){ Transaction storage transaction = txList.transactions[i]; require(!transaction.executed); // solium-disable-line error-reason transaction.executed = true; transaction.target.call.value(transaction.value)(transaction.data); // solium-disable-line security/no-call-value } sumDeposit = 0; lastAction = now; submissionCounter[round] = 0; } else { status = Status.DisputeCreated; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); disputeID = arbitrator.createDispute.value(arbitrationCost)(txLists.length, arbitratorExtraData); sumDeposit = sumDeposit.subCap(arbitrationCost); // Freeze lastAction time so there would be no submissions untill the dispute is resolved. lastAction = 0; round++; } } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if all submitted lists are fully funded.. * @param _submissionID The ID that was given to the list upon submission. */ function fundAppeal(uint _submissionID) public payable{ require(_submissionID > 0 && _submissionID <= submissionCounter[0], "ID is out of range"); require(status == Status.DisputeCreated, "No dispute to appeal"); require(arbitrator.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Appealable, "Dispute is not appealable."); (uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(disputeID); // The last third of the appeal period is secured so it'd be possible to create an appeal manually if more than one but not all submitted lists have been funded. require( now - appealPeriodStart < (appealPeriodEnd - appealPeriodStart) * 2/3, "Appeal fees must be paid within the two thirds of appeal period." ); TransactionList storage txList = txLists[submissions[_submissionID]]; require(txList.sender == msg.sender, "Can't fund the list created by someone else"); if (round > 1){ require(txList.appealFeePaid[round - 1], "Can't participate if didn't pay appeal fee in previous round"); } require(!txList.appealFeePaid[round], "Appeal fee has already been paid"); bool winner; uint multiplier; if (arbitrator.currentRuling(disputeID) == _submissionID){ winner = true; multiplier = winnerStakeMultiplier; } else if (arbitrator.currentRuling(disputeID) == 0){ multiplier = sharedStakeMultiplier; } else { multiplier = loserStakeMultiplier; } require(winner || (now - appealPeriodStart < (appealPeriodEnd - appealPeriodStart)/3), "The loser must pay during the first third of the appeal period."); uint appealCost = arbitrator.appealCost(disputeID, arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); require(msg.value >= totalCost, "Not enough ETH to cover appeal cost"); txList.appealFeePaid[round] = true; submissionCounter[round]++; uint remainder = msg.value - totalCost; if (remainder > 0) require(txList.sender.send(remainder), "Couldn't sent leftover ETH"); // Create an appeal if every side is funded. if(submissionCounter[round] == submissionCounter[round - 1]){ arbitrator.appeal.value(appealCost)(disputeID, arbitratorExtraData); round++; } } /** @dev Allows to manually create an appeal if more than one but not all submitted lists are funded. * Note that this function is only executable during the last third of the appeal period in order to know how many submitted lists have been funded. */ function appeal()public { require(status == Status.DisputeCreated, "No dispute to appeal"); require(arbitrator.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Appealable, "Dispute is not appealable."); (uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(disputeID); require( now - appealPeriodStart >= (appealPeriodEnd - appealPeriodStart) * 2/3 && now < appealPeriodEnd, "Appeal must be raised in the last third of appeal period." ); require(submissionCounter[round] > 1, "Not enough submissions to create an appeal"); uint appealCost = arbitrator.appealCost(disputeID, arbitratorExtraData); round++; arbitrator.appeal.value(appealCost)(disputeID, arbitratorExtraData); } /** @dev Gives a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { require(msg.sender == address(arbitrator), "Must be called by the arbitrator"); require(status == Status.DisputeCreated, "The dispute has already been resolved"); // Override the decision if one of the submitted lists was a duplicate with lower submission time or if it was the only side that paid appeal fee. uint ruling = _ruling; for (uint i = 1; i <= submissionCounter[0]; i++){ if (i == ruling){ continue; } if (txLists[submissions[i]].listHash == txLists[submissions[ruling]].listHash && txLists[submissions[i]].submissionTime < txLists[submissions[ruling]].submissionTime || txLists[submissions[i]].appealFeePaid[round] && submissionCounter[round] == 1){ ruling = i; } } executeRuling(_disputeID, ruling); } /** @dev Executes a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal{ // Nothing is executed if arbitrator refused to arbitrate. if(_ruling != 0){ TransactionList storage txList = txLists[submissions[_ruling]]; for (uint i = 0; i < txList.txCounter; i++){ Transaction storage transaction = txList.transactions[i]; require(!transaction.executed); // solium-disable-line error-reason transaction.executed = true; transaction.target.call.value(transaction.value)(transaction.data); // solium-disable-line security/no-call-value } // The reward is the submission deposit of losing parties minus arbitration fee. uint reward = sumDeposit.subCap(txList.deposit); require(txList.sender.send(reward), "Was unable to send reward"); } sumDeposit = 0; lastAction = now; status = Status.NoDispute; for (i = 0; i <= round; i++){ submissionCounter[i] = 0; } round = 0; disputeID = 0; } /** @dev Gets the info of the specified transaction in the specified list. * @param _listID The index of the transaction list in the array of lists. * @param _transactionIndex The index of the transaction. * @return The transaction info. */ function getTransactionInfo(uint _listID, uint _transactionIndex) public view returns ( uint ID, address target, uint value, bytes data, bool executed ) { TransactionList storage txList = txLists[_listID]; Transaction storage transaction = txList.transactions[_transactionIndex]; return ( transaction.ID, transaction.target, transaction.value, transaction.data, transaction.executed ); } /** @dev Returns true if the specified list in the specified round was funded. * Note that for a dispute round this function will return false but it's not an issue since disputes are automatically funded with submission deposits anyway. * @param _listID The index of the transaction list in the array of lists. * @param _round The round of the dispute. * @return Whether or not the appeal fee has been paid. */ function isAppealFeePaid(uint _listID, uint _round) public view returns(bool){ return txLists[_listID].appealFeePaid[_round]; } }
* @dev Executes a ruling of a dispute. @param _disputeID ID of the dispute in the Arbitrator contract. @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision"./ Nothing is executed if arbitrator refused to arbitrate.
function executeRuling(uint _disputeID, uint _ruling) internal{ if(_ruling != 0){ TransactionList storage txList = txLists[submissions[_ruling]]; for (uint i = 0; i < txList.txCounter; i++){ Transaction storage transaction = txList.transactions[i]; transaction.executed = true; } require(txList.sender.send(reward), "Was unable to send reward"); } sumDeposit = 0; lastAction = now; status = Status.NoDispute; for (i = 0; i <= round; i++){ submissionCounter[i] = 0; } round = 0; disputeID = 0; }
12,868,824
[ 1, 9763, 279, 436, 332, 310, 434, 279, 1015, 2507, 18, 282, 389, 2251, 2507, 734, 1599, 434, 326, 1015, 2507, 316, 326, 1201, 3682, 86, 639, 6835, 18, 282, 389, 86, 332, 310, 534, 332, 310, 864, 635, 326, 10056, 86, 639, 18, 3609, 716, 374, 353, 8735, 364, 315, 1248, 7752, 19, 17369, 310, 358, 1221, 279, 14604, 9654, 19, 13389, 353, 7120, 309, 10056, 86, 639, 1278, 3668, 358, 10056, 5141, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 54, 332, 310, 12, 11890, 389, 2251, 2507, 734, 16, 2254, 389, 86, 332, 310, 13, 2713, 95, 203, 3639, 309, 24899, 86, 332, 310, 480, 374, 15329, 203, 5411, 5947, 682, 2502, 2229, 682, 273, 2229, 7432, 63, 25675, 63, 67, 86, 332, 310, 13563, 31, 203, 5411, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 2229, 682, 18, 978, 4789, 31, 277, 27245, 95, 203, 7734, 5947, 2502, 2492, 273, 2229, 682, 18, 20376, 63, 77, 15533, 203, 7734, 2492, 18, 4177, 4817, 273, 638, 31, 203, 203, 5411, 289, 203, 5411, 2583, 12, 978, 682, 18, 15330, 18, 4661, 12, 266, 2913, 3631, 315, 14992, 13496, 358, 1366, 19890, 8863, 203, 3639, 289, 203, 3639, 2142, 758, 1724, 273, 374, 31, 203, 3639, 1142, 1803, 273, 2037, 31, 203, 3639, 1267, 273, 2685, 18, 2279, 1669, 2507, 31, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 1648, 3643, 31, 277, 27245, 95, 203, 5411, 8515, 4789, 63, 77, 65, 273, 374, 31, 203, 3639, 289, 203, 3639, 3643, 273, 374, 31, 203, 3639, 1015, 2507, 734, 273, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 4/20 baby (2021) */ // SPDX-License-Identifier: MIT // Total supply: 420 Billion // 4.20% Tax : // - 4% Burn // - 0.2% Charity // // NO ONE SHOULD BE IN JAIL FOR SMOKING A NATURAL SHRUB // THAT’S WHY 0.2% OF ALL TRANSACTIONS WILL GO TOWARDS ENDING THIS INJUSTICE AND SECURING WORLDWIDE LEGALISATION // Community project aiming to support those who have found themselves in trouble because of the sacred bush // STRIVING FOR LEGALISATION // Twitter: @StarDogeToken // Telegram: https://t.me/StarDogeToken // Discord: https://discord.gg/esqSpHFU // ╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗───╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗───╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗─ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣ // β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£β”€β”€β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£β”€β”€β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£ // β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β•β”€β”€β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β•β”€β”€β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β• // β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€β”€β”€β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€β”€β”€β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€ // _________________00___________________________________00___________________________________00__________________________ // ________________0000_________________________________0000_________________________________0000_________________________ // _______________000000_______________________________000000_______________________________000000________________________ // ____00_________000000__________00________00_________000000__________00________00_________000000__________00____________ // _____0000______000000______00000__________0000______000000______00000__________0000______000000______00000_____________ // _____000000____0000000___0000000__________000000____0000000___0000000__________000000____0000000___0000000_____________ // ______000000___0000000_0000000_____________000000___0000000_0000000_____________000000___0000000_0000000_______________ // _______0000000_000000_0000000_______________0000000_000000_0000000_______________0000000_000000_0000000________________ // _________000000_00000_000000__________________000000_00000_000000__________________000000_00000_000000_________________ // _0000_____000000_000_0000__000000000__0000_____000000_000_0000__000000000__0000_____000000_000_0000__000000000_________ // __000000000__0000_0_000_000000000______000000000__0000_0_000_000000000______000000000__0000_0_000_000000000____________ // _____000000000__0_0_0_000000000___________000000000__0_0_0_000000000___________000000000__0_0_0_000000000______________ // _________0000000000000000_____________________0000000000000000_____________________0000000000000000____________________ // ______________000_0_0000___________________________000_0_0000___________________________000_0_0000_____________________ // ____________00000_0__00000_______________________00000_0__00000_______________________00000_0__00000___________________ // ___________00_____0______00_____________________00_____0______00_____________________00_____0______00__________________ 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. */ // File: @openzeppelin/contracts/utils/Context.sol abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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. */ // File: @openzeppelin/contracts/access/Ownable.sol contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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. */ // File: @openzeppelin/contracts/math/SafeMath.sol 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; } } /** * @dev Collection of functions related to the address type */ // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } /** * @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}. */ // File: contracts/ERC20.sol contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) internal _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 { } } // ╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗───╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗───╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗─ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣ // β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£β”€β”€β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£β”€β”€β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£ // β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β•β”€β”€β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β•β”€β”€β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β• // β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€β”€β”€β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€β”€β”€β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€ // StarDoge Contract contract StarDoge is ERC20, Ownable { address public creator = msg.sender; uint256 public burnFee = 400; uint256 public charityFee = 20; address public charityWallet = 0x49c4efDa8794E86FAAE0d1dB8FEcbDCCCD046199; address public developerWallet = 0xA8E01767A346490F1b0647EE5d027F589d5855df; constructor() public ERC20("StarDoge", "StarDoge") { _mint(msg.sender, 420000000000000000000000000000); // 420000000000 } // Transfer recipient recives amount - fee function transfer(address recipient, uint256 amount) public override returns (bool) { uint256 burnAmount = burnFee.mul(amount).div(10000); uint256 charityAmount = charityFee.mul(amount).div(10000); uint256 taxAmount = burnAmount.add(charityAmount); uint256 transferAmount = amount.sub(taxAmount); // Burn and Charity cut _burn(msg.sender, burnAmount); _transfer(msg.sender, charityWallet, charityAmount); // Transfer _transfer(msg.sender, recipient, transferAmount); return true; } // TransferFrom recipient recives amount, sender's account is debited amount + fee function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { uint256 burnAmount = burnFee.mul(amount).div(10000); uint256 charityAmount = charityFee.mul(amount).div(10000); uint256 taxAmount = burnAmount.add(charityAmount); uint256 transferAmount = amount.sub(taxAmount); // Burn and Charity cut _burn(sender, burnAmount); _transfer(sender, charityWallet, charityAmount); // Transfer _transfer(sender, recipient, transferAmount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } // Set Transfers function burnTransfer(uint256 amount) public returns (bool) { _splitPayment(amount, 10000, 0, 0); return true; } function charityTransfer(uint256 amount) public returns (bool) { _splitPayment(amount, 0, 10000, 0); return true; } function devTransfer(uint256 amount) public returns (bool) { _splitPayment(amount, 0, 0, 10000); return true; } function nfTransfer(uint256 amount) public returns (bool) { _splitPayment(amount, 4000, 4000, 2000); return true; } // Multi transfer function function _multiTransfer(address[] calldata wallets, uint256 amount) public returns (bool) { require(msg.sender == creator, 'Must be contract owner'); for (uint256 i = 0; i < wallets.length; i++) { _transfer(msg.sender, wallets[i], amount); } return true; } // Function for split proportions function _splitPayment(uint256 amount, uint256 burnProp, uint256 charityProp, uint256 devProp) public returns (bool) { require(burnProp.add(charityProp).add(devProp) == 10000, 'Proportions must sum to 10000'); uint256 burnAmount = burnProp.mul(amount).div(10000); uint256 charityAmount = charityProp.mul(amount).div(10000); uint256 developerAmount = devProp.mul(amount).div(10000); // Burn. Charity and Developer cut _burn(msg.sender, burnAmount); _transfer(msg.sender, charityWallet, charityAmount); _transfer(msg.sender, developerWallet, developerAmount); return true; } } // ╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗───╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗───╔╦╗─╔╦╗─╔╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╦╗─╔╦╦╦╦╦╗─ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╬╩╩╬╬╗ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╦╦╦╦╗─╠╬╬╦╦╦╦╗─╠╬╣──╠╬╣ // ╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣──╠╬╣─╠╬╣─╠╬╣─╠╬╬╩╩╩╩╝─╠╬╬╩╩╩╩╝─╠╬╣──╠╬╣ // β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£β”€β”€β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£β”€β”€β•šβ•¬β•£β”€β• β•¬β•£β”€β• β•¬β•β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β”€β”€β”€β”€β• β•¬β•£β”€β”€β• β•¬β•£ // β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β•β”€β”€β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β•β”€β”€β”€β•šβ•¬β•¦β•¬β•©β•¬β•¦β•¬β•β”€β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¦β•¦β•—β”€β• β•¬β•¬β•¦β•¦β•¬β•¬β• // β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€β”€β”€β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€β”€β”€β”€β”€β•šβ•©β•β”€β•šβ•©β•β”€β”€β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•©β•β”€β•šβ•©β•©β•©β•©β•©β•β”€
TransferFrom recipient recives amount, sender's account is debited amount + fee Burn and Charity cut Transfer
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { uint256 burnAmount = burnFee.mul(amount).div(10000); uint256 charityAmount = charityFee.mul(amount).div(10000); uint256 taxAmount = burnAmount.add(charityAmount); uint256 transferAmount = amount.sub(taxAmount); _burn(sender, burnAmount); _transfer(sender, charityWallet, charityAmount); _transfer(sender, recipient, transferAmount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
10,461,091
[ 1, 5912, 1265, 8027, 1950, 3606, 3844, 16, 5793, 1807, 2236, 353, 443, 3682, 329, 3844, 397, 14036, 605, 321, 471, 3703, 560, 6391, 12279, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 18305, 6275, 273, 18305, 14667, 18, 16411, 12, 8949, 2934, 2892, 12, 23899, 1769, 203, 3639, 2254, 5034, 1149, 560, 6275, 273, 1149, 560, 14667, 18, 16411, 12, 8949, 2934, 2892, 12, 23899, 1769, 203, 3639, 2254, 5034, 5320, 6275, 273, 18305, 6275, 18, 1289, 12, 3001, 560, 6275, 1769, 203, 3639, 2254, 5034, 7412, 6275, 273, 3844, 18, 1717, 12, 8066, 6275, 1769, 203, 540, 203, 3639, 389, 70, 321, 12, 15330, 16, 18305, 6275, 1769, 203, 3639, 389, 13866, 12, 15330, 16, 1149, 560, 16936, 16, 1149, 560, 6275, 1769, 203, 540, 203, 3639, 389, 13866, 12, 15330, 16, 8027, 16, 7412, 6275, 1769, 203, 540, 203, 3639, 389, 12908, 537, 12, 15330, 16, 1234, 18, 15330, 16, 389, 5965, 6872, 63, 15330, 6362, 3576, 18, 15330, 8009, 1717, 12, 8949, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 1699, 1359, 7923, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; contract Arrays2 { uint256[][3] fixedMultiArray; uint256[2][] dynamicMultiArray; uint256[] storageDynamicArray; // Tipo uint[] storage ref (all'interno di una funzione) function multidimensional() public { uint256[4] memory memArray = [uint256(6), 7, 8, 9]; fixedMultiArray[0] = memArray; fixedMultiArray[1] = new uint256[](4); fixedMultiArray[2] = [1, 2, 3, 4, 5]; //dynamicMultiArray = memArray; // Errore dynamicMultiArray = new uint256[2][](3); // Istanziare un array dinamico nello storage con new (Memoria allo storage) dynamicMultiArray[0] = [1, 2]; dynamicMultiArray[1] = [3, 4]; dynamicMultiArray[2] = [5, 6]; // dynamicMultiArray[3] = [7,8]; // Errore, non possibile da estendere } function conv() public { uint256[3] memory memArray = [uint256(6), 7, 8]; // Tipo uint[] memory uint256[] storage localStorageDynamicArray; // Tipo uint[] storage pointer storageDynamicArray = new uint256[](3); storageDynamicArray = memArray; // localStorageDynamicArray = new uint[](3); // Errore // localStorageDynamicArray = memArray; // Errore localStorageDynamicArray = storageDynamicArray; } // PARAMS function params(uint256[] memory paramsArray) public { // Anche con memory/calldata storageDynamicArray = paramsArray; // Copia l'intero memory/calldata array nello storage } function mutliParams(uint256[2][2] memory paramsArray) public { // Anche con memory/calldata } function mutliParams(uint256[][2] memory paramsArray) public { // Anche con memory/calldata (Illegale senza ABICoderV2) } function mutliParams(uint256[2][] memory paramsArray) public { // Anche con memory/calldata } function mutliParams(uint256[][] memory paramsArray) public { // Anche con memory/calldata (Illegale senza ABICoderV2) } // RETURNS BYTES/STRING ARRAY (Sono bidimensionali) function retBytes(bytes[] memory s) public returns (bytes[] memory) {} function retString(string[] memory s) public returns (string[] memory) {} }
Anche con memory/calldata
function mutliParams(uint256[2][] memory paramsArray) public { }
2,527,375
[ 1, 979, 18706, 356, 3778, 19, 1991, 892, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 4318, 549, 1370, 12, 11890, 5034, 63, 22, 6362, 65, 3778, 859, 1076, 13, 1071, 288, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/421613/0xb63234AcaC10029EAebF63A0f28584cd096dF62B/sources/project_/contracts/GarbiMining.sol
veGRB each block. The total point for all pools The block when mining start
contract GarbiMining is Ownable{ using SafeMath for uint256; IERC20withMint public veGRB; uint256 public totalAllocPoint = 1000; uint256 public startBlock; PoolInfo[] public poolInfo; mapping(uint256 => mapping(address => uint256)) public rewardDebtOf; uint public constant GRACE_PERIOD = 30 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; uint public delay; mapping(bytes32 => TimeLock) public timeLockOf; struct TimeLock { bool queuedTransactions; uint256 timeOfExecute; mapping(bytes32 => address) addressOf; mapping(bytes32 => uint256) uintOf; } struct PoolInfo { uint256 allocPoint; } event onHarvest(uint256 _pid, address _user, uint256 _amt); event onQueuedTransactionsChangeAddress(string _functionName, string _fieldName, address _value); event onQueuedTransactionsChangeUint(string _functionName, string _fieldName, uint256 _value); event onQueuedTransactionSsetPoolPoint(uint256 _pid, uint256 _allocPoint); event onCancelTransactions(string _functionName); constructor( IERC20withMint _vegrb, uint256 _startBlock ) { veGRB = _vegrb; startBlock = _startBlock; } function setDelay(uint delay_) public onlyOwner { require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; } function cancelTransactions(string memory _functionName) public onlyOwner { TimeLock storage _timelock = timeLockOf[keccak256(abi.encode(_functionName))]; _timelock.queuedTransactions = false; emit onCancelTransactions(_functionName); } function queuedTransactionsChangeAddress(string memory _functionName, string memory _fieldName, address _newAddr) public onlyOwner { TimeLock storage _timelock = timeLockOf[keccak256(abi.encode(_functionName))]; _timelock.addressOf[keccak256(abi.encode(_fieldName))] = _newAddr; _timelock.queuedTransactions = true; _timelock.timeOfExecute = block.timestamp.add(delay); emit onQueuedTransactionsChangeAddress(_functionName, _fieldName, _newAddr); } function queuedTransactionsChangeUint(string memory _functionName, string memory _fieldName, uint256 _value) public onlyOwner { TimeLock storage _timelock = timeLockOf[keccak256(abi.encode(_functionName))]; _timelock.uintOf[keccak256(abi.encode(_fieldName))] = _value; _timelock.queuedTransactions = true; _timelock.timeOfExecute = block.timestamp.add(delay); emit onQueuedTransactionsChangeUint(_functionName, _fieldName, _value); } function queuedTransactionSsetPoolPoint(uint256 _pid, uint256 _allocPoint) public onlyOwner { TimeLock storage _timelock = timeLockOf[keccak256(abi.encode('setPoolPoint', _pid))]; _timelock.uintOf[keccak256(abi.encode('allocPoint'))] = _allocPoint; _timelock.queuedTransactions = true; _timelock.timeOfExecute = block.timestamp.add(delay); emit onQueuedTransactionSsetPoolPoint(_pid, _allocPoint); } function setTotalBlockPerDay() public onlyOwner { TimeLock storage _timelock = timeLockOf[keccak256(abi.encode('setTotalBlockPerDay'))]; _validateTimelock(_timelock); require(_timelock.uintOf[keccak256(abi.encode('totalBlockPerDay'))] > 0, "INVALID_AMOUNT"); totalBlockPerDay = _timelock.uintOf[keccak256(abi.encode('totalBlockPerDay'))]; delete _timelock.uintOf[keccak256(abi.encode('totalBlockPerDay'))]; _timelock.queuedTransactions = false; } function setTotalAllocPoint() public onlyOwner { TimeLock storage _timelock = timeLockOf[keccak256(abi.encode('setTotalAllocPoint'))]; _validateTimelock(_timelock); require(_timelock.uintOf[keccak256(abi.encode('totalAllocPoint'))] > 0, "INVALID_AMOUNT"); totalAllocPoint = _timelock.uintOf[keccak256(abi.encode('totalAllocPoint'))]; delete _timelock.uintOf[keccak256(abi.encode('totalAllocPoint'))]; _timelock.queuedTransactions = false; } function setGarbiTokenContract() public onlyOwner { TimeLock storage _timelock = timeLockOf[keccak256(abi.encode('setGarbiTokenContract'))]; _validateTimelock(_timelock); require(_timelock.addressOf[keccak256(abi.encode('veGRB'))] != address(0), "INVALID_ADDRESS"); veGRB = IERC20withMint(_timelock.addressOf[keccak256(abi.encode('veGRB'))]); delete _timelock.addressOf[keccak256(abi.encode('veGRB'))]; _timelock.queuedTransactions = false; } 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; } 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; } function setPoolPoint(uint256 _pid) public onlyOwner { TimeLock storage _timelock = timeLockOf[keccak256(abi.encode('setPoolPoint', _pid))]; _validateTimelock(_timelock); require(poolInfo[_pid].allocPoint != _timelock.uintOf[keccak256(abi.encode('allocPoint'))], 'INVALID_INPUT'); updatePool(_pid); poolInfo[_pid].allocPoint = _timelock.uintOf[keccak256(abi.encode('allocPoint'))]; delete _timelock.uintOf[keccak256(abi.encode('allocPoint'))]; _timelock.queuedTransactions = false; } function _validateTimelock(TimeLock storage _timelock) private view { require(_timelock.queuedTransactions == true, "Transaction hasn't been queued."); require(_timelock.timeOfExecute <= block.timestamp, "Transaction hasn't surpassed time lock."); require(_timelock.timeOfExecute.add(GRACE_PERIOD) >= block.timestamp, "Transaction is stale."); } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 _totalShare = pool.grabiFarm.totalShare(); uint256 _multiplier = getBlockFrom(pool.lastRewardBlock, block.number); uint256 _reward = _multiplier.mul(vegrbPerBlock).mul(pool.allocPoint).div(totalAllocPoint); if (_totalShare == 0) { pool.lastRewardBlock = block.number; return; } veGRB.mint(address(this), _reward); pool.accVeGRBPerShare = pool.accVeGRBPerShare.add(_reward.mul(1e12).div(_totalShare)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 _totalShare = pool.grabiFarm.totalShare(); uint256 _multiplier = getBlockFrom(pool.lastRewardBlock, block.number); uint256 _reward = _multiplier.mul(vegrbPerBlock).mul(pool.allocPoint).div(totalAllocPoint); if (_totalShare == 0) { pool.lastRewardBlock = block.number; return; } veGRB.mint(address(this), _reward); pool.accVeGRBPerShare = pool.accVeGRBPerShare.add(_reward.mul(1e12).div(_totalShare)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 _totalShare = pool.grabiFarm.totalShare(); uint256 _multiplier = getBlockFrom(pool.lastRewardBlock, block.number); uint256 _reward = _multiplier.mul(vegrbPerBlock).mul(pool.allocPoint).div(totalAllocPoint); if (_totalShare == 0) { pool.lastRewardBlock = block.number; return; } veGRB.mint(address(this), _reward); pool.accVeGRBPerShare = pool.accVeGRBPerShare.add(_reward.mul(1e12).div(_totalShare)); pool.lastRewardBlock = block.number; } function harvest(uint256 _pid, address _user) external returns(uint256 _pendingVeGRB) { updatePool(_pid); uint256 _rewardDebt; (_pendingVeGRB, _rewardDebt, ) = getUserInfo(_pid, _user); uint256 _vegrbBal = veGRB.balanceOf(address(this)); rewardDebtOf[_pid][_user] = _rewardDebt; if (_pendingVeGRB > _vegrbBal) { _pendingVeGRB = _vegrbBal; } if (_pendingVeGRB > 0) { veGRB.transfer(_user, _pendingVeGRB); emit onHarvest(_pid, _user, _pendingVeGRB); } } function harvest(uint256 _pid, address _user) external returns(uint256 _pendingVeGRB) { updatePool(_pid); uint256 _rewardDebt; (_pendingVeGRB, _rewardDebt, ) = getUserInfo(_pid, _user); uint256 _vegrbBal = veGRB.balanceOf(address(this)); rewardDebtOf[_pid][_user] = _rewardDebt; if (_pendingVeGRB > _vegrbBal) { _pendingVeGRB = _vegrbBal; } if (_pendingVeGRB > 0) { veGRB.transfer(_user, _pendingVeGRB); emit onHarvest(_pid, _user, _pendingVeGRB); } } function harvest(uint256 _pid, address _user) external returns(uint256 _pendingVeGRB) { updatePool(_pid); uint256 _rewardDebt; (_pendingVeGRB, _rewardDebt, ) = getUserInfo(_pid, _user); uint256 _vegrbBal = veGRB.balanceOf(address(this)); rewardDebtOf[_pid][_user] = _rewardDebt; if (_pendingVeGRB > _vegrbBal) { _pendingVeGRB = _vegrbBal; } if (_pendingVeGRB > 0) { veGRB.transfer(_user, _pendingVeGRB); emit onHarvest(_pid, _user, _pendingVeGRB); } } function updateUser(uint256 _pid, address _user) public returns(bool) { PoolInfo memory pool = poolInfo[_pid]; require(address(pool.grabiFarm) == msg.sender, 'INVALID_PERMISSION'); uint256 _userShare = pool.grabiFarm.shareOf(_user); rewardDebtOf[_pid][_user] = _userShare.mul(pool.accVeGRBPerShare).div(1e12); return true; } function poolLength() external view returns (uint256) { return poolInfo.length; } function getBlockFrom(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } function getMiningSpeedOf(uint256 _pid) public view returns(uint256) { return poolInfo[_pid].allocPoint.mul(100).div(totalAllocPoint); } function getTotalMintPerDayOf(uint256 _pid) public view returns(uint256) { return totalBlockPerDay.mul(vegrbPerBlock).mul(poolInfo[_pid].allocPoint).div(totalAllocPoint); } function getVeGRBAddr() public view returns(address) { return address(veGRB); } function getUserInfo(uint256 _pid, address _user) public view returns (uint256 _pendingVeGRB, uint256 _rewardDebt, uint256 _userShare) { PoolInfo memory pool = poolInfo[_pid]; uint256 accVeGRBPerShare = pool.accVeGRBPerShare; uint256 _totalShare = pool.grabiFarm.totalShare(); _userShare = pool.grabiFarm.shareOf(_user); if (block.number > pool.lastRewardBlock && _totalShare != 0) { uint256 _multiplier = getBlockFrom(pool.lastRewardBlock, block.number); uint256 _reward = _multiplier.mul(vegrbPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVeGRBPerShare = accVeGRBPerShare.add(_reward.mul(1e12).div(_totalShare)); } _rewardDebt = _userShare.mul(accVeGRBPerShare).div(1e12); if (_rewardDebt > rewardDebtOf[_pid][_user]) { _pendingVeGRB = _rewardDebt.sub(rewardDebtOf[_pid][_user]); } } function getUserInfo(uint256 _pid, address _user) public view returns (uint256 _pendingVeGRB, uint256 _rewardDebt, uint256 _userShare) { PoolInfo memory pool = poolInfo[_pid]; uint256 accVeGRBPerShare = pool.accVeGRBPerShare; uint256 _totalShare = pool.grabiFarm.totalShare(); _userShare = pool.grabiFarm.shareOf(_user); if (block.number > pool.lastRewardBlock && _totalShare != 0) { uint256 _multiplier = getBlockFrom(pool.lastRewardBlock, block.number); uint256 _reward = _multiplier.mul(vegrbPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVeGRBPerShare = accVeGRBPerShare.add(_reward.mul(1e12).div(_totalShare)); } _rewardDebt = _userShare.mul(accVeGRBPerShare).div(1e12); if (_rewardDebt > rewardDebtOf[_pid][_user]) { _pendingVeGRB = _rewardDebt.sub(rewardDebtOf[_pid][_user]); } } function getUserInfo(uint256 _pid, address _user) public view returns (uint256 _pendingVeGRB, uint256 _rewardDebt, uint256 _userShare) { PoolInfo memory pool = poolInfo[_pid]; uint256 accVeGRBPerShare = pool.accVeGRBPerShare; uint256 _totalShare = pool.grabiFarm.totalShare(); _userShare = pool.grabiFarm.shareOf(_user); if (block.number > pool.lastRewardBlock && _totalShare != 0) { uint256 _multiplier = getBlockFrom(pool.lastRewardBlock, block.number); uint256 _reward = _multiplier.mul(vegrbPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVeGRBPerShare = accVeGRBPerShare.add(_reward.mul(1e12).div(_totalShare)); } _rewardDebt = _userShare.mul(accVeGRBPerShare).div(1e12); if (_rewardDebt > rewardDebtOf[_pid][_user]) { _pendingVeGRB = _rewardDebt.sub(rewardDebtOf[_pid][_user]); } } function getAddressChangeOnTimeLock(string memory _functionName, string memory _fieldName) public view returns(address) { return timeLockOf[keccak256(abi.encode(_functionName))].addressOf[keccak256(abi.encode(_fieldName))]; } function getUintChangeOnTimeLock(string memory _functionName, string memory _fieldName) public view returns(uint256) { return timeLockOf[keccak256(abi.encode(_functionName))].uintOf[keccak256(abi.encode(_fieldName))]; } }
11,566,607
[ 1, 537, 6997, 38, 1517, 1203, 18, 1021, 2078, 1634, 364, 777, 16000, 1021, 1203, 1347, 1131, 310, 787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 611, 6779, 77, 2930, 310, 353, 14223, 6914, 95, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 654, 39, 3462, 1918, 49, 474, 1071, 10489, 6997, 38, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 8763, 2148, 273, 4336, 31, 203, 565, 2254, 5034, 1071, 787, 1768, 31, 203, 203, 565, 8828, 966, 8526, 1071, 2845, 966, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 19890, 758, 23602, 951, 31, 203, 203, 565, 2254, 1071, 5381, 611, 9254, 67, 28437, 273, 5196, 4681, 31, 203, 565, 2254, 1071, 5381, 6989, 18605, 67, 26101, 273, 576, 4681, 31, 203, 565, 2254, 1071, 5381, 4552, 18605, 67, 26101, 273, 5196, 4681, 31, 203, 565, 2254, 1071, 4624, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 2647, 2531, 13, 1071, 813, 2531, 951, 31, 203, 203, 203, 565, 1958, 2647, 2531, 288, 203, 3639, 1426, 12234, 14186, 31, 203, 3639, 2254, 5034, 813, 951, 5289, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 1758, 13, 1758, 951, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 2254, 951, 31, 203, 565, 289, 203, 377, 203, 565, 1958, 8828, 966, 288, 203, 3639, 2254, 5034, 4767, 2148, 31, 1171, 203, 565, 289, 203, 203, 565, 871, 603, 44, 297, 26923, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 16, 2254, 5034, 389, 301, 88, 1769, 203, 203, 565, 871, 603, 21039, 14186, 3043, 1887, 12, 1080, 389, 915, 2 ]
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @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)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/utils/Utils.sol /** * @title Utilities Contract * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; contract Utils { /** MODIFIERS **/ /** * @notice Check if the address is not zero */ modifier onlyValidAddress(address _address) { require(_address != address(0), "Invalid address"); _; } /** * @notice Check if the address is not the sender's address */ modifier isSenderNot(address _address) { require(_address != msg.sender, "Address is the same as the sender"); _; } /** * @notice Check if the address is the sender's address */ modifier isSender(address _address) { require(_address == msg.sender, "Address is different from the sender"); _; } /** * @notice Controle if a boolean attribute (false by default) was updated to true. * @dev This attribute is designed specifically for recording an action. * @param criterion The boolean attribute that records if an action has taken place */ modifier onlyOnce(bool criterion) { require(criterion == false, "Already been set"); _; criterion = true; } } // File: contracts/utils/Managed.sol pragma solidity ^0.5.7; contract Managed is Utils, Ownable { // managers can be set and altered by owner, multiple manager accounts are possible mapping(address => bool) public isManager; /** EVENTS **/ event ChangedManager(address indexed manager, bool active); /*** MODIFIERS ***/ modifier onlyManager() { require(isManager[msg.sender], "not manager"); _; } /** * @dev Set / alter manager / whitelister "account". This can be done from owner only * @param manager address address of the manager to create/alter * @param active bool flag that shows if the manager account is active */ function setManager(address manager, bool active) public onlyOwner onlyValidAddress(manager) { isManager[manager] = active; emit ChangedManager(manager, active); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @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); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @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 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _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 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 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 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 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 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)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @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); } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.2; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(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); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.2; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.2; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.2; /** * Utility library of inline functions on addresses */ library Address { /** * 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 account address of the account to check * @return whether the target address is a contract */ function isContract(address account) 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.2; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(address(this), spender) == 0)); 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 equal true). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } // File: contracts/utils/Reclaimable.sol /** * @title Reclaimable * @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to * the token contract. The recovered token will be sent to the owner of token. * @author Validity Labs AG <[email protected]> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.7; contract Reclaimable is Ownable { using SafeERC20 for IERC20; /** * @notice Let the owner to retrieve other tokens accidentally sent to this contract. * @dev This function is suitable when no token of any kind shall be stored under * the address of the inherited contract. * @param tokenToBeRecovered address of the token to be recovered. */ function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner { uint256 balance = tokenToBeRecovered.balanceOf(address(this)); tokenToBeRecovered.safeTransfer(msg.sender, balance); } } // File: openzeppelin-solidity/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.2; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(msg.sender); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(msg.sender)); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(msg.sender); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol pragma solidity ^0.5.2; /** * @title WhitelistedRole * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(msg.sender)); _; } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(msg.sender); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/token/ERC20/library/Snapshots.sol /** * @title Snapshot * @dev Utility library of the Snapshot structure, including getting value. * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; library Snapshots { using Math for uint256; using SafeMath for uint256; /** * @notice This structure stores the historical value associate at a particular timestamp * @param timestamp The timestamp of the creation of the snapshot * @param value The value to be recorded */ struct Snapshot { uint256 timestamp; uint256 value; } struct SnapshotList { Snapshot[] history; } /** TODO: within 1 block: transfer w/ snapshot, then dividend distrubtion, transfer w/ snapshot * * @notice This function creates snapshots for certain value... * @dev To avoid having two Snapshots with the same block.timestamp, we check if the last * existing one is the current block.timestamp, we update the last Snapshot * @param item The SnapshotList to be operated * @param _value The value associated the the item that is going to have a snapshot */ function createSnapshot(SnapshotList storage item, uint256 _value) internal { uint256 length = item.history.length; if (length == 0 || (item.history[length.sub(1)].timestamp < block.timestamp)) { item.history.push(Snapshot(block.timestamp, _value)); } else { // When the last existing snapshot is ready to be updated item.history[length.sub(1)].value = _value; } } /** * @notice Find the index of the item in the SnapshotList that contains information * corresponding to the timestamp. (FindLowerBond of the array) * @dev The binary search logic is inspired by the Arrays.sol from Openzeppelin * @param item The list of Snapshots to be queried * @param timestamp The timestamp of the queried moment * @return The index of the Snapshot array */ function findBlockIndex( SnapshotList storage item, uint256 timestamp ) internal view returns (uint256) { // Find lower bound of the array uint256 length = item.history.length; // Return value for extreme cases: If no snapshot exists and/or the last snapshot if (item.history[length.sub(1)].timestamp <= timestamp) { return length.sub(1); } else { // Need binary search for the value uint256 low = 0; uint256 high = length.sub(1); while (low < high.sub(1)) { uint256 mid = Math.average(low, high); // mid will always be strictly less than high and it rounds down if (item.history[mid].timestamp <= timestamp) { low = mid; } else { high = mid; } } return low; } } /** * @notice This function returns the value of the corresponding Snapshot * @param item The list of Snapshots to be queried * @param timestamp The timestamp of the queried moment * @return The value of the queried moment */ function getValueAt( SnapshotList storage item, uint256 timestamp ) internal view returns (uint256) { if (item.history.length == 0 || timestamp < item.history[0].timestamp) { return 0; } else { uint256 index = findBlockIndex(item, timestamp); return item.history[index].value; } } } // File: contracts/token/ERC20/ERC20Snapshot.sol /** * @title ERC20 Snapshot Token * @dev This is an ERC20 compatible token that takes snapshots of account balances. * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; contract ERC20Snapshot is ERC20 { using Snapshots for Snapshots.SnapshotList; mapping(address => Snapshots.SnapshotList) private _snapshotBalances; Snapshots.SnapshotList private _snapshotTotalSupply; event CreatedAccountSnapshot(address indexed account, uint256 indexed timestamp, uint256 value); event CreatedTotalSupplySnapshot(uint256 indexed timestamp, uint256 value); /** * @notice Return the historical supply of the token at a certain time * @param timestamp The block number of the moment when token supply is queried * @return The total supply at "timestamp" */ function totalSupplyAt(uint256 timestamp) public view returns (uint256) { return _snapshotTotalSupply.getValueAt(timestamp); } /** * @notice Return the historical balance of an account at a certain time * @param owner The address of the token holder * @param timestamp The block number of the moment when token supply is queried * @return The balance of the queried token holder at "timestamp" */ function balanceOfAt(address owner, uint256 timestamp) public view returns (uint256) { return _snapshotBalances[owner].getValueAt(timestamp); } /** OVERRIDE * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @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 { super._transfer(from, to, value); // ERC20 transfer _createAccountSnapshot(from, balanceOf(from)); _createAccountSnapshot(to, balanceOf(to)); } /** OVERRIDE * @notice Mint tokens to one account while enforcing the update of Snapshots * @param account The address that receives tokens * @param value The amount of tokens to be created */ function _mint(address account, uint256 value) internal { super._mint(account, value); _createAccountSnapshot(account, balanceOf(account)); _createTotalSupplySnapshot(account, totalSupplyAt(block.timestamp).add(value)); } /** OVERRIDE * @notice Burn tokens of one account * @param account The address whose tokens will be burnt * @param value The amount of tokens to be burnt */ function _burn(address account, uint256 value) internal { super._burn(account, value); _createAccountSnapshot(account, balanceOf(account)); _createTotalSupplySnapshot(account, totalSupplyAt(block.timestamp).sub(value)); } /** * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { _snapshotTotalSupply.createSnapshot(amount); emit CreatedTotalSupplySnapshot(block.timestamp, amount); } /** * @notice creates an account snapshot & emits event * @param amount uint256 * @param account address */ function _createAccountSnapshot(address account, uint256 amount) internal { _snapshotBalances[account].createSnapshot(amount); emit CreatedAccountSnapshot(account, block.timestamp, amount); } function _precheckSnapshot() internal { // FILL LATER TODO: comment on how this is utilized // Why it's not being abstract } } // File: contracts/STO/token/WhitelistedSnapshot.sol /** * @title Whitelisted Snapshot Token * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; /** * Whitelisted Snapshot repurposes the following 2 variables inherited from ERC20Snapshot: * _snapshotBalances: only whitelisted accounts get snapshots * _snapshotTotalSupply: only the total sum of whitelisted */ contract WhitelistedSnapshot is ERC20Snapshot, WhitelistedRole { /** OVERRIDE * @notice add account to whitelist & create a snapshot of current balance * @param account address */ function addWhitelisted(address account) public { super.addWhitelisted(account); uint256 balance = balanceOf(account); _createAccountSnapshot(account, balance); uint256 newSupplyValue = totalSupplyAt(now).add(balance); _createTotalSupplySnapshot(account, newSupplyValue); } /** OVERRIDE * @notice remove account from white & create a snapshot of 0 balance * @param account address */ function removeWhitelisted(address account) public { super.removeWhitelisted(account); _createAccountSnapshot(account, 0); uint256 balance = balanceOf(account); uint256 newSupplyValue = totalSupplyAt(now).sub(balance); _createTotalSupplySnapshot(account, newSupplyValue); } /** OVERRIDE & call parent * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @dev the super._transfer call handles the snapshot of each account. See the internal functions * below: _createTotalSupplySnapshot & _createAccountSnapshot * @param from address The address to transfer from * @param to address The address to transfer to * @param value uint256 The amount to be transferred */ function _transfer(address from, address to, uint256 value) internal { // if available will call the sibiling's inherited function before calling the parent's super._transfer(from, to, value); /** * Possibilities: * Homogeneous Transfers: * 0: _whitelist to _whitelist: 0 total supply snapshot * 1: nonwhitelist to nonwhitelist: 0 total supply snapshot * Heterogeneous Transfers: * 2: _whitelist to nonwhitelist: 1 whitelisted total supply snapshot * 3: nonwhitelist to _whitelist: 1 whitelisted total supply snapshot */ // isWhitelistedHetero tells us to/from is a mix of whitelisted/not whitelisted accounts // isAdding tell us whether or not to add or subtract from the whitelisted total supply value (bool isWhitelistedHetero, bool isAdding) = _isWhitelistedHeterogeneousTransfer(from, to); if (isWhitelistedHetero) { // one account is whitelisted, the other is not uint256 newSupplyValue = totalSupplyAt(block.timestamp); address account; if (isAdding) { newSupplyValue = newSupplyValue.add(value); account = to; } else { newSupplyValue = newSupplyValue.sub(value); account = from; } _createTotalSupplySnapshot(account, newSupplyValue); } } /** * @notice returns true (isHetero) for a mix-match of whitelisted & nonwhitelisted account transfers * returns true (isAdding) if total supply is increasing or false for decreasing * @param from address * @param to address * @return isHetero, isAdding. bool, bool */ function _isWhitelistedHeterogeneousTransfer(address from, address to) internal view returns (bool isHetero, bool isAdding) { bool _isToWhitelisted = isWhitelisted(to); bool _isFromWhitelisted = isWhitelisted(from); if (!_isFromWhitelisted && _isToWhitelisted) { isHetero = true; isAdding = true; // increase whitelisted total supply } else if (_isFromWhitelisted && !_isToWhitelisted) { isHetero = true; } } /** OVERRIDE * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { if (isWhitelisted(account)) { super._createTotalSupplySnapshot(account, amount); } } /** OVERRIDE * @notice only snapshot if account is whitelisted * @param account address * @param amount uint256 */ function _createAccountSnapshot(address account, uint256 amount) internal { if (isWhitelisted(account)) { super._createAccountSnapshot(account, amount); } } function _precheckSnapshot() internal onlyWhitelisted {} } // File: contracts/STO/BaseOptedIn.sol /** * @title Base Opt In * @author Validity Labs AG <[email protected]> * This allows accounts to "opt out" or "opt in" * Defaults everyone to opted in * Example: opt out from onchain dividend payments */ pragma solidity ^0.5.7; contract BaseOptedIn { // uint256 = timestamp. Default: 0 = opted in. > 0 = opted out mapping(address => uint256) public optedOutAddresses; // whitelisters who've opted to receive offchain dividends /** EVENTS **/ event OptedOut(address indexed account); event OptedIn(address indexed account); modifier onlyOptedBool(bool isIn) { // true for onlyOptedIn, false for onlyOptedOut if (isIn) { require(optedOutAddresses[msg.sender] > 0, "already opted in"); } else { require(optedOutAddresses[msg.sender] == 0, "already opted out"); } _; } /** * @notice accounts who have opted out from onchain dividend payments */ function optOut() public onlyOptedBool(false) { optedOutAddresses[msg.sender] = block.timestamp; emit OptedOut(msg.sender); } /** * @notice accounts who previously opted out, who opt back in */ function optIn() public onlyOptedBool(true) { optedOutAddresses[msg.sender] = 0; emit OptedIn(msg.sender); } /** * @notice returns true if opted in * @param account address * @return optedIn bool */ function isOptedIn(address account) public view returns (bool optedIn) { if (optedOutAddresses[account] == 0) { optedIn = true; } } } // File: contracts/STO/token/OptedInSnapshot.sol /** * @title Opted In Snapshot * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; /** * Opted In Snapshot repurposes the following 2 variables inherited from ERC20Snapshot: * _snapshotBalances: snapshots of opted in accounts * _snapshotTotalSupply: only the total sum of opted in accounts */ contract OptedInSnapshot is ERC20Snapshot, BaseOptedIn { /** OVERRIDE * @notice accounts who previously opted out, who opt back in */ function optIn() public { // protects against TODO: Fill later super._precheckSnapshot(); super.optIn(); address account = msg.sender; uint256 balance = balanceOf(account); _createAccountSnapshot(account, balance); _createTotalSupplySnapshot(account, totalSupplyAt(now).add(balance)); } /** OVERRIDE * @notice call parent f(x) & * create new snapshot for account: setting to 0 * create new shapshot for total supply: oldTotalSupply.sub(balance) */ function optOut() public { // protects against TODO: Fill later super._precheckSnapshot(); super.optOut(); address account = msg.sender; _createAccountSnapshot(account, 0); _createTotalSupplySnapshot(account, totalSupplyAt(now).sub(balanceOf(account))); } /** OVERRIDE * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @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 { // if available will call the sibiling's inherited function before calling the parent's super._transfer(from, to, value); /** * Possibilities: * Homogeneous Transfers: * 0: opted in to opted in: 0 total supply snapshot * 1: opted out to opted out: 0 total supply snapshot * Heterogeneous Transfers: * 2: opted out to opted in: 1 whitelisted total supply snapshot * 3: opted in to opted out: 1 whitelisted total supply snapshot */ // isOptedHetero tells us to/from is a mix of opted in/out accounts // isAdding tell us whether or not to add or subtract from the opted in total supply value (bool isOptedHetero, bool isAdding) = _isOptedHeterogeneousTransfer(from, to); if (isOptedHetero) { // one account is whitelisted, the other is not uint256 newSupplyValue = totalSupplyAt(block.timestamp); address account; if (isAdding) { newSupplyValue = newSupplyValue.add(value); account = to; } else { newSupplyValue = newSupplyValue.sub(value); account = from; } _createTotalSupplySnapshot(account, newSupplyValue); } } /** * @notice returns true for a mix-match of opted in & opted out transfers. * if true, returns true/false for increasing either optedIn or opetedOut total supply balances * @dev should only be calling if both to and from accounts are whitelisted * @param from address * @param to address * @return isOptedHetero, isOptedInIncrease. bool, bool */ function _isOptedHeterogeneousTransfer(address from, address to) internal view returns (bool isOptedHetero, bool isOptedInIncrease) { bool _isToOptedIn = isOptedIn(to); bool _isFromOptedIn = isOptedIn(from); if (!_isFromOptedIn && _isToOptedIn) { isOptedHetero = true; isOptedInIncrease = true; // increase opted in total supply } else if (_isFromOptedIn && !_isToOptedIn) { isOptedHetero = true; } } /** OVERRIDE * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { if (isOptedIn(account)) { super._createTotalSupplySnapshot(account, amount); } } /** OVERRIDE * @notice only snapshot if opted in * @param account address * @param amount uint256 */ function _createAccountSnapshot(address account, uint256 amount) internal { if (isOptedIn(account)) { super._createAccountSnapshot(account, amount); } } } // File: contracts/STO/token/ERC20ForceTransfer.sol /** * @title ERC20 ForceTransfer * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; /** * @dev inherit contract, create external/public function that calls these internal functions * to activate the ability for one or both forceTransfer implementations */ contract ERC20ForceTransfer is Ownable, ERC20 { event ForcedTransfer(address indexed confiscatee, uint256 amount, address indexed receiver); /** * @notice takes all funds from confiscatee and sends them to receiver * @param confiscatee address who's funds are being confiscated * @param receiver address who's receiving the funds */ function forceTransfer(address confiscatee, address receiver) external onlyOwner { uint256 balance = balanceOf(confiscatee); _transfer(confiscatee, receiver, balance); emit ForcedTransfer(confiscatee, balance, receiver); } /** * @notice takes an amount of funds from confiscatee and sends them to receiver * @param confiscatee address who's funds are being confiscated * @param receiver address who's receiving the funds */ function forceTransfer(address confiscatee, address receiver, uint256 amount) external onlyOwner { _transfer(confiscatee, receiver, amount); emit ForcedTransfer(confiscatee, amount, receiver); } } // File: contracts/STO/BaseDocumentRegistry.sol /** * @title Base Document Registry Contract * @author Validity Labs AG <[email protected]> * inspired by Neufund's iAgreement smart contract */ pragma solidity ^0.5.7; // solhint-disable not-rely-on-time contract BaseDocumentRegistry is Ownable { using SafeMath for uint256; struct HashedDocument { uint256 timestamp; string documentUri; } HashedDocument[] private _documents; event AddedLogDocumented(string documentUri, uint256 documentIndex); /** * @notice adds a document's uri from IPFS to the array * @param documentUri string */ function addDocument(string calldata documentUri) external onlyOwner { require(bytes(documentUri).length > 0, "invalid documentUri"); HashedDocument memory document = HashedDocument({ timestamp: block.timestamp, documentUri: documentUri }); _documents.push(document); emit AddedLogDocumented(documentUri, _documents.length.sub(1)); } /** * @notice fetch the latest document on the array * @return uint256, string, uint256 */ function currentDocument() public view returns (uint256 timestamp, string memory documentUri, uint256 index) { require(_documents.length > 0, "no documents exist"); uint256 last = _documents.length.sub(1); HashedDocument storage document = _documents[last]; return (document.timestamp, document.documentUri, last); } /** * @notice adds a document's uri from IPFS to the array * @param documentIndex uint256 * @return uint256, string, uint256 */ function getDocument(uint256 documentIndex) public view returns (uint256 timestamp, string memory documentUri, uint256 index) { require(documentIndex < _documents.length, "invalid index"); HashedDocument storage document = _documents[documentIndex]; return (document.timestamp, document.documentUri, documentIndex); } /** * @notice return the total amount of documents in the array * @return uint256 */ function documentCount() public view returns (uint256) { return _documents.length; } } // File: contracts/examples/ExampleSecurityToken.sol /** * @title Example Security Token * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; contract ExampleSecurityToken is Utils, Reclaimable, ERC20Detailed, WhitelistedSnapshot, OptedInSnapshot, ERC20Mintable, ERC20Burnable, ERC20Pausable, ERC20ForceTransfer, BaseDocumentRegistry { bool private _isSetup; /** * @notice contructor for the token contract */ constructor(string memory name, string memory symbol, address initialAccount, uint256 initialBalance) public ERC20Detailed(name, symbol, 0) { // pause(); _mint(initialAccount, initialBalance); roleSetup(initialAccount); } /** * @notice setup roles and contract addresses for the new token * @param board Address of the owner who is also a manager */ function roleSetup(address board) internal onlyOwner onlyOnce(_isSetup) { addMinter(board); addPauser(board); _addWhitelistAdmin(board); } /** OVERRIDE - onlyOwner role (the board) can call * @notice Burn tokens of one account * @param account The address whose tokens will be burnt * @param value The amount of tokens to be burnt */ function _burn(address account, uint256 value) internal onlyOwner { super._burn(account, value); } } // File: contracts/STO/dividends/Dividends.sol /** * @title Dividend contract for STO * @author Validity Labs AG <[email protected]> */ pragma solidity ^0.5.7; contract Dividends is Utils, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; address public _wallet; // set at deploy time struct Dividend { uint256 recordDate; // timestamp of the record date uint256 claimPeriod; // claim period, in seconds, of the claiming period address payoutToken; // payout token, which could be different each time. uint256 payoutAmount; // the total amount of tokens deposit uint256 claimedAmount; // the total amount of tokens being claimed uint256 totalSupply; // the total supply of sto token when deposit was made bool reclaimed; // If the unclaimed deposit was reclaimed by the team mapping(address => bool) claimed; // If investors have claimed their dividends. } address public _token; Dividend[] public dividends; // Record the balance of each ERC20 token deposited to this contract as dividends. mapping(address => uint256) public totalBalance; // EVENTS event DepositedDividend(uint256 indexed dividendIndex, address indexed payoutToken, uint256 payoutAmount, uint256 recordDate, uint256 claimPeriod); event ReclaimedDividend(uint256 indexed dividendIndex, address indexed claimer, uint256 claimedAmount); event RecycledDividend(uint256 indexed dividendIndex, uint256 timestamp, uint256 recycledAmount); /** * @notice Check if the index is valid */ modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length, "Such dividend does not exist"); _; } /** * @notice initialize the Dividend contract with the STO Token contract and the new owner * @param stoToken The token address, of which the holders could claim dividends. * @param wallet the address of the wallet to receive the reclaimed funds */ /* solhint-disable */ constructor(address stoToken, address wallet) public onlyValidAddress(stoToken) onlyValidAddress(wallet) { _token = stoToken; _wallet = wallet; transferOwnership(wallet); } /* solhint-enable */ /** * @notice deposit payoutDividend tokens (ERC20) into this contract * @param payoutToken ERC20 address of the token used for payout the current dividend * @param amount uint256 total amount of the ERC20 tokens deposited to payout to all * token holders as of previous block from when this function is included * @dev The owner should first call approve(STODividendsContractAddress, amount) * in the payoutToken contract */ function depositDividend(address payoutToken, uint256 recordDate, uint256 claimPeriod, uint256 amount) public onlyOwner onlyValidAddress(payoutToken) { require(amount > 0, "invalid deposit amount"); require(recordDate > 0, "invalid recordDate"); require(claimPeriod > 0, "invalid claimPeriod"); IERC20(payoutToken).safeTransferFrom(msg.sender, address(this), amount); // transfer ERC20 to this contract totalBalance[payoutToken] = totalBalance[payoutToken].add(amount); // update global balance of ERC20 token dividends.push( Dividend( recordDate, claimPeriod, payoutToken, amount, 0, ERC20Snapshot(_token).totalSupplyAt(block.timestamp), //eligible supply false ) ); emit DepositedDividend((dividends.length).sub(1), payoutToken, amount, block.timestamp, claimPeriod); } /** TODO: check for "recycle" or "recycled" - replace with reclaimed * @notice Token holder claim their dividends * @param dividendIndex The index of the deposit dividend to be claimed. */ function claimDividend(uint256 dividendIndex) public validDividendIndex(dividendIndex) { Dividend storage dividend = dividends[dividendIndex]; require(dividend.claimed[msg.sender] == false, "Dividend already claimed"); require(dividend.reclaimed == false, "Dividend already reclaimed"); require((dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp, "No longer claimable"); _claimDividend(dividendIndex, msg.sender); } /** * @notice Claim dividends from a startingIndex to all possible dividends * @param startingIndex The index from which the loop of claiming dividend starts * @dev To claim all dividends from the beginning, set this value to 0. * This parameter may help reducing the risk of running out-of-gas due to many loops */ function claimAllDividends(uint256 startingIndex) public validDividendIndex(startingIndex) { for (uint256 i = startingIndex; i < dividends.length; i++) { Dividend storage dividend = dividends[i]; if (dividend.claimed[msg.sender] == false && (dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp && dividend.reclaimed == false) { _claimDividend(i, msg.sender); } } } /** * @notice recycle the dividend. Transfer tokens back to the _wallet * @param dividendIndex the storage index of the dividend in the pushed array. */ function reclaimDividend(uint256 dividendIndex) public onlyOwner validDividendIndex(dividendIndex) { Dividend storage dividend = dividends[dividendIndex]; require(dividend.reclaimed == false, "Dividend already reclaimed"); require((dividend.recordDate).add(dividend.claimPeriod) < block.timestamp, "Still claimable"); dividend.reclaimed = true; uint256 recycledAmount = (dividend.payoutAmount).sub(dividend.claimedAmount); totalBalance[dividend.payoutToken] = totalBalance[dividend.payoutToken].sub(recycledAmount); IERC20(dividend.payoutToken).safeTransfer(_wallet, recycledAmount); emit RecycledDividend(dividendIndex, block.timestamp, recycledAmount); } /** * @notice get dividend info at index * @param dividendIndex the storage index of the dividend in the pushed array. * @return recordDate (uint256) of the dividend * @return claimPeriod (uint256) of the dividend * @return payoutToken (address) of the dividend * @return payoutAmount (uint256) of the dividend * @return claimedAmount (uint256) of the dividend * @return the total supply (uint256) of the dividend * @return Whether this dividend was reclaimed (bool) of the dividend */ function getDividend(uint256 dividendIndex) public view validDividendIndex(dividendIndex) returns (uint256, uint256, address, uint256, uint256, uint256, bool) { Dividend memory result = dividends[dividendIndex]; return ( result.recordDate, result.claimPeriod, address(result.payoutToken), result.payoutAmount, result.claimedAmount, result.totalSupply, result.reclaimed); } /** * @notice Internal function that claim the dividend * @param dividendIndex the index of the dividend to be claimed * @param account address of the account to receive dividend */ function _claimDividend(uint256 dividendIndex, address account) internal { Dividend storage dividend = dividends[dividendIndex]; uint256 claimAmount = _calcClaim(dividendIndex, account); dividend.claimed[account] = true; dividend.claimedAmount = (dividend.claimedAmount).add(claimAmount); totalBalance[dividend.payoutToken] = totalBalance[dividend.payoutToken].sub(claimAmount); IERC20(dividend.payoutToken).safeTransfer(account, claimAmount); emit ReclaimedDividend(dividendIndex, account, claimAmount); } /** * @notice calculate dividend claim amount */ function _calcClaim(uint256 dividendIndex, address account) internal view returns (uint256) { Dividend memory dividend = dividends[dividendIndex]; uint256 balance = ERC20Snapshot(_token).balanceOfAt(account, dividend.recordDate); return balance.mul(dividend.payoutAmount).div(dividend.totalSupply); } } // File: contracts/examples/ExampleTokenFactory.sol /** * @title Example Token Factory Contract * @author Validity Labs AG <[email protected]> */ pragma solidity 0.5.7; /* solhint-disable max-line-length */ /* solhint-disable separate-by-one-line-in-contract */ contract ExampleTokenFactory is Managed { mapping(address => address) public tokenToDividend; /*** EVENTS ***/ event DeployedToken(address indexed contractAddress, string name, string symbol, address indexed clientOwner); event DeployedDividend(address indexed contractAddress); /*** FUNCTIONS ***/ function newToken(string calldata _name, string calldata _symbol, address _clientOwner, uint256 _initialAmount) external onlyOwner { address tokenAddress = _deployToken(_name, _symbol, _clientOwner, _initialAmount); } function newTokenAndDividend(string calldata _name, string calldata _symbol, address _clientOwner, uint256 _initialAmount) external onlyOwner { address tokenAddress = _deployToken(_name, _symbol, _clientOwner, _initialAmount); address dividendAddress = _deployDividend(tokenAddress, _clientOwner); tokenToDividend[tokenAddress] = dividendAddress; } /** MANGER FUNCTIONS **/ /** * @notice Prospectus and Quarterly Reports * @dev string null check is done at the token level - see ERC20DocumentRegistry * @param _est address of the targeted EST * @param _documentUri string IPFS URI to the document */ function addDocument(address _est, string calldata _documentUri) external onlyValidAddress(_est) onlyManager { ExampleSecurityToken(_est).addDocument(_documentUri); } /** * @notice pause or unpause individual EST * @param _est address of the targeted EST */ function togglePauseEST(address _est) public onlyValidAddress(_est) onlyManager { ExampleSecurityToken est = ExampleSecurityToken(_est); bool result = est.paused(); result ? est.unpause() : est.pause(); } /** * @notice force the transfer of tokens from _confiscatee to _receiver * @param _est address of the targeted EST * @param _confiscatee address to confiscate tokens from * @param _receiver address to receive the balance of tokens * @param _amount uint256 amount to take away from _confiscatee */ function forceTransferEST(address _est, address _confiscatee, address _receiver, uint256 _amount) public onlyValidAddress(_est) onlyValidAddress(_confiscatee) onlyValidAddress(_receiver) onlyManager { require(_amount > 0, "invalid amount"); ExampleSecurityToken est = ExampleSecurityToken(_est); est.forceTransfer(_confiscatee, _receiver, _amount); } function _deployToken(string memory _name, string memory _symbol, address _clientOwner, uint256 _initialAmount) internal returns (address) { require(bytes(_name).length > 0, "name cannot be blank"); require(bytes(_symbol).length > 0, "symbol cannot be blank"); ExampleSecurityToken tokenContract = new ExampleSecurityToken(_name, _symbol, _clientOwner, _initialAmount); emit DeployedToken(address(tokenContract), _name, _symbol, _clientOwner); return address(tokenContract); } function _deployDividend(address tokenAddress, address wallet) internal returns (address) { Dividends dividendContract = new Dividends(tokenAddress, wallet); emit DeployedDividend(address(dividendContract)); return address(dividendContract); } }
* @notice Check if the index is valid/
modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length, "Such dividend does not exist"); _; }
5,444,880
[ 1, 1564, 309, 326, 770, 353, 923, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 923, 7244, 26746, 1016, 12, 11890, 5034, 389, 2892, 26746, 1016, 13, 288, 203, 3639, 2583, 24899, 2892, 26746, 1016, 411, 3739, 350, 5839, 18, 2469, 16, 315, 5464, 31945, 1552, 486, 1005, 8863, 203, 3639, 389, 31, 203, 565, 289, 7010, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x851B31013E321069cc04Ee3b907EC3Eba524B244/sources/src/callbacks/UniFiCallback.sol
@notice UniFi swap callback @param amount0 - The change in token0 reserves from the swap. @param amount1 - The change in token1 reserves from the swap. @param data - The data packed into the swap.
function unifiCall(address, uint256 amount0, uint256 amount1, bytes calldata data) external { (bool _zeroForOne, address _tokenIn, uint24 _swapFee) = abi.decode(data, (bool, address, uint24)); uint256 amountOut = _zeroForOne ? amount1 : amount0; (uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(msg.sender).getReserves(); uint256 amountIn = OracleLibraryV2.getAmountIn( amountOut, _zeroForOne ? reserve0 : reserve1, _zeroForOne ? reserve1 : reserve0, _swapFee ); IERC20(_tokenIn).transfer(msg.sender, amountIn);
17,109,117
[ 1, 984, 77, 42, 77, 7720, 1348, 225, 3844, 20, 300, 1021, 2549, 316, 1147, 20, 400, 264, 3324, 628, 326, 7720, 18, 225, 3844, 21, 300, 1021, 2549, 316, 1147, 21, 400, 264, 3324, 628, 326, 7720, 18, 225, 501, 300, 1021, 501, 12456, 1368, 326, 7720, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 640, 704, 1477, 12, 2867, 16, 2254, 5034, 3844, 20, 16, 2254, 5034, 3844, 21, 16, 1731, 745, 892, 501, 13, 3903, 288, 203, 3639, 261, 6430, 389, 7124, 1290, 3335, 16, 1758, 389, 2316, 382, 16, 2254, 3247, 389, 22270, 14667, 13, 273, 24126, 18, 3922, 12, 892, 16, 261, 6430, 16, 1758, 16, 2254, 3247, 10019, 203, 203, 3639, 2254, 5034, 3844, 1182, 273, 389, 7124, 1290, 3335, 692, 3844, 21, 294, 3844, 20, 31, 203, 3639, 261, 11890, 17666, 20501, 20, 16, 2254, 17666, 20501, 21, 16, 13, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 3576, 18, 15330, 2934, 588, 607, 264, 3324, 5621, 203, 203, 3639, 2254, 5034, 3844, 382, 273, 28544, 9313, 58, 22, 18, 588, 6275, 382, 12, 203, 5411, 3844, 1182, 16, 389, 7124, 1290, 3335, 692, 20501, 20, 294, 20501, 21, 16, 389, 7124, 1290, 3335, 692, 20501, 21, 294, 20501, 20, 16, 389, 22270, 14667, 203, 3639, 11272, 203, 3639, 467, 654, 39, 3462, 24899, 2316, 382, 2934, 13866, 12, 3576, 18, 15330, 16, 3844, 382, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x13AC7770e0287b905E4f27BddC72463fBE2Ce75d/sources/browser/HopOnYOP.sol
15% reward for 60 days lock
uint8 constant public reward2 = 15; uint256 constant public stakedFor2 = 60 days;
8,094,860
[ 1, 3600, 9, 19890, 364, 4752, 4681, 2176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 28, 5381, 1071, 19890, 22, 273, 4711, 31, 2254, 5034, 5381, 1071, 384, 9477, 1290, 22, 273, 4752, 4681, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @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); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @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. * @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 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)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts 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 signed integers, reverts 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; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * 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 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _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 An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _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 returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(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 returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * 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 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 * 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 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 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 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 { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // The functionality that all derivative contracts expose to the admin. interface AdminInterface { // Initiates the shutdown process, in case of an emergency. function emergencyShutdown() external; // A core contract method called immediately before or after any financial transaction. It pays fees and moves money // between margin accounts to make sure they reflect the NAV of the contract. function remargin() external; } contract ExpandedIERC20 is IERC20 { // Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless. function burn(uint value) external; // Mints tokens and adds them to the balance of the `to` address. // Note: this method should be permissioned to only allow designated parties to mint tokens. function mint(address to, uint value) external; } // This interface allows derivative contracts to pay Oracle fees for their use of the system. interface StoreInterface { // Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH. function payOracleFees() external payable; // Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an // ERC20 token rather than ETH. All approved tokens are transfered. function payOracleFeesErc20(address erc20Address) external; // Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the // maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the // price feed in their favor. function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount); } interface ReturnCalculatorInterface { // Computes the return between oldPrice and newPrice. function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn); // Gets the effective leverage for the return calculator. // Note: if this parameter doesn't exist for this calculator, this method should return 1. function leverage() external view returns (int _leverage); } // This interface allows contracts to query unverified prices. interface PriceFeedInterface { // Whether this PriceFeeds provides prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have // been published for this identifier. function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price); // An event fired when a price is published. event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price); } contract AddressWhitelist is Ownable { enum Status { None, In, Out } mapping(address => Status) private whitelist; address[] private whitelistIndices; // Adds an address to the whitelist function addToWhitelist(address newElement) external onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddToWhitelist(newElement); } // Removes an address from the whitelist. function removeFromWhitelist(address elementToRemove) external onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemoveFromWhitelist(elementToRemove); } } // Checks whether an address is on the whitelist. function isOnWhitelist(address elementToCheck) external view returns (bool) { return whitelist[elementToCheck] == Status.In; } // Gets all addresses that are currently included in the whitelist // Note: This method skips over, but still iterates through addresses. // It is possible for this call to run out of gas if a large number of // addresses have been removed. To prevent this unlikely scenario, we can // modify the implementation so that when addresses are removed, the last addresses // in the array is moved to the empty index. function getWhitelist() external view returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } event AddToWhitelist(address indexed addedAddress); event RemoveFromWhitelist(address indexed removedAddress); } contract Withdrawable is Ownable { // Withdraws ETH from the contract. function withdraw(uint amount) external onlyOwner { msg.sender.transfer(amount); } // Withdraws ERC20 tokens from the contract. function withdrawErc20(address erc20Address, uint amount) external onlyOwner { IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } } // This interface allows contracts to query a verified, trusted price. interface OracleInterface { // Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available. // Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if // the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this // method. function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable); // Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if // the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call // this method. function getPrice(bytes32 identifier, uint time) external view returns (int price); // Returns whether the Oracle provides verified prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // An event fired when a request for a (identifier, time) pair is made. event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time); // An event fired when a verified price is available for a (identifier, time) pair. event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price); } interface RegistryInterface { struct RegisteredDerivative { address derivativeAddress; address derivativeCreator; } // Registers a new derivative. Only authorized derivative creators can call this method. function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; // Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call // this method. function addDerivativeCreator(address derivativeCreator) external; // Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this // method. function removeDerivativeCreator(address derivativeCreator) external; // Returns whether the derivative has been registered with the registry (and is therefore an authorized participant // in the UMA system). function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); // Returns a list of all derivatives that are associated with a particular party. function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives); // Returns all registered derivatives. function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives); // Returns whether an address is authorized to register new derivatives. function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized); } contract Registry is RegistryInterface, Withdrawable { using SafeMath for uint; // Array of all registeredDerivatives that are approved to use the UMA Oracle. RegisteredDerivative[] private registeredDerivatives; // This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered. enum PointerValidity { Invalid, Valid, WasValid } struct Pointer { PointerValidity valid; uint128 index; } // Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives. mapping(address => Pointer) private derivativePointers; // Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied // like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose // of the Pointer struct and break separation of concern between referential data and data. struct PartiesMap { mapping(address => bool) parties; } // Maps from derivative address to the set of parties that are involved in that derivative. mapping(address => PartiesMap) private derivativesToParties; // Maps from derivative creator address to whether that derivative creator has been approved to register contracts. mapping(address => bool) private derivativeCreators; modifier onlyApprovedDerivativeCreator { require(derivativeCreators[msg.sender]); _; } function registerDerivative(address[] calldata parties, address derivativeAddress) external onlyApprovedDerivativeCreator { // Create derivative pointer. Pointer storage pointer = derivativePointers[derivativeAddress]; // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double // registered). require(pointer.valid == PointerValidity.Invalid); pointer.valid = PointerValidity.Valid; registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender)); // No length check necessary because we should never hit (2^127 - 1) derivatives. pointer.index = uint128(registeredDerivatives.length.sub(1)); // Set up PartiesMap for this derivative. PartiesMap storage partiesMap = derivativesToParties[derivativeAddress]; for (uint i = 0; i < parties.length; i = i.add(1)) { partiesMap.parties[parties[i]] = true; } address[] memory partiesForEvent = parties; emit RegisterDerivative(derivativeAddress, partiesForEvent); } function addDerivativeCreator(address derivativeCreator) external onlyOwner { if (!derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = true; emit AddDerivativeCreator(derivativeCreator); } } function removeDerivativeCreator(address derivativeCreator) external onlyOwner { if (derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = false; emit RemoveDerivativeCreator(derivativeCreator); } } function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) { return derivativePointers[derivative].valid == PointerValidity.Valid; } function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) { // This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long // as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy // the array over to the return array, which is allocated using the correct size. Note: this is done by double // copying each value rather than storing some referential info (like indices) in memory to reduce the number // of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1). RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length); uint outputIndex = 0; for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) { RegisteredDerivative storage derivative = registeredDerivatives[i]; if (derivativesToParties[derivative.derivativeAddress].parties[party]) { // Copy selected derivative to the temporary array. tmpDerivativeArray[outputIndex] = derivative; outputIndex = outputIndex.add(1); } } // Copy the temp array to the return array that is set to the correct size. derivatives = new RegisteredDerivative[](outputIndex); for (uint j = 0; j < outputIndex; j = j.add(1)) { derivatives[j] = tmpDerivativeArray[j]; } } function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) { return registeredDerivatives; } function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) { return derivativeCreators[derivativeCreator]; } event RegisterDerivative(address indexed derivativeAddress, address[] parties); event AddDerivativeCreator(address indexed addedDerivativeCreator); event RemoveDerivativeCreator(address indexed removedDerivativeCreator); } contract Testable is Ownable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } modifier onlyIfTest { require(isTest); _; } function setCurrentTime(uint _time) external onlyOwner onlyIfTest { currentTime = _time; } function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract ContractCreator is Withdrawable { Registry internal registry; address internal oracleAddress; address internal storeAddress; address internal priceFeedAddress; constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress) public { registry = Registry(registryAddress); oracleAddress = _oracleAddress; storeAddress = _storeAddress; priceFeedAddress = _priceFeedAddress; } function _registerContract(address[] memory parties, address contractToRegister) internal { registry.registerDerivative(parties, contractToRegister); } } library TokenizedDerivativeParams { enum ReturnType { Linear, Compound } struct ConstructorParams { address sponsor; address admin; address oracle; address store; address priceFeed; uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying price that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of margin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18 ReturnType returnType; uint startingUnderlyingPrice; uint creationTime; } } // TokenizedDerivativeStorage: this library name is shortened due to it being used so often. library TDS { enum State { // The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as // it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state. // Possible state transitions: Disputed, Expired, Defaulted. Live, // Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in // time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn. // The resolution of these states moves the contract to the Settled state. Remargining is not allowed. // The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the // Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short // account. Otherwise, the dispute fee is added to the long margin account. // Possible state transitions: Settled. Disputed, // Contract expiration has been reached. // Possible state transitions: Settled. Expired, // The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and // move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to // Settled. // Possible state transitions: Settled. Defaulted, // UMA has manually triggered a shutdown of the account. // Possible state transitions: Settled. Emergency, // Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be // created, and contract can't remargin. // Possible state transitions: None. Settled } // The state of the token at a particular time. The state gets updated on remargin. struct TokenState { int underlyingPrice; int tokenPrice; uint time; } // The information in the following struct is only valid if in the midst of a Dispute. struct Dispute { int disputedNav; uint deposit; } struct WithdrawThrottle { uint startTime; uint remainingWithdrawal; } struct FixedParameters { // Fixed contract parameters. uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move that the long is protected against. uint disputeDeposit; // Percentage of margin requirement * 10^18 uint fixedFeePerSecond; // Percentage of nav*10^18 uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18 bytes32 product; TokenizedDerivativeParams.ReturnType returnType; uint initialTokenUnderlyingRatio; uint creationTime; string symbol; } struct ExternalAddresses { // Other addresses/contracts address sponsor; address admin; address apDelegate; OracleInterface oracle; StoreInterface store; PriceFeedInterface priceFeed; ReturnCalculatorInterface returnCalculator; IERC20 marginCurrency; } struct Storage { FixedParameters fixedParameters; ExternalAddresses externalAddresses; // Balances int shortBalance; int longBalance; State state; uint endTime; // The NAV of the contract always reflects the transition from (`prev`, `current`). // In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev` // and `latest` -> `current` (and then recompute). // In the case of a dispute, `current` might change (which is why we have to hold on to `prev`). TokenState referenceTokenState; TokenState currentTokenState; int nav; // Net asset value is measured in Wei Dispute disputeInfo; // Only populated once the contract enters a frozen state. int defaultPenaltyAmount; WithdrawThrottle withdrawThrottle; } } library TokenizedDerivativeUtils { using TokenizedDerivativeUtils for TDS.Storage; using SafeMath for uint; using SignedSafeMath for int; uint private constant SECONDS_PER_DAY = 86400; uint private constant SECONDS_PER_YEAR = 31536000; uint private constant INT_MAX = 2**255 - 1; uint private constant UINT_FP_SCALING_FACTOR = 10**18; int private constant INT_FP_SCALING_FACTOR = 10**18; modifier onlySponsor(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor); _; } modifier onlyAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrApDelegate(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); _; } // Contract initializer. Should only be called at construction. // Note: Must be a public function because structs cannot be passed as calldata (required data type for external // functions). function _initialize( TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public { s._setFixedParameters(params, symbol); s._setExternalAddresses(params); // Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally // creating rounding or overflow errors. require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9)); require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9)); // TODO(mrice32): we should have an ideal start time rather than blindly polling. (uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); // If nonzero, take the user input as the starting price. if (params.startingUnderlyingPrice != 0) { latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice); } require(latestUnderlyingPrice > 0); require(latestTime != 0); // Keep the ratio in case it's needed for margin computation. s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice)); require(s.fixedParameters.initialTokenUnderlyingRatio != 0); // Set end time to max value of uint to implement no expiry. if (params.expiry == 0) { s.endTime = ~uint(0); } else { require(params.expiry >= latestTime); s.endTime = params.expiry; } s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice); s.state = TDS.State.Live; } function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { s._remarginInternal(); int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (newTokenNav < 0) { newTokenNav = 0; } uint positiveTokenNav = _safeUintCast(newTokenNav); // Get any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). uint refund = s._pullSentMargin(marginForPurchase); // Subtract newTokenNav from amount sent. uint depositAmount = marginForPurchase.sub(positiveTokenNav); // Deposit additional margin into the short account. s._depositInternal(depositAmount); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. This should be 0 in this case, // but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure // the sender never loses money. refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav)); // Send the accumulated refund. s._sendMargin(refund); } function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external { require(s.state == TDS.State.Live || s.state == TDS.State.Settled); require(tokensToRedeem > 0); if (s.state == TDS.State.Live) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); s._remarginInternal(); require(s.state == TDS.State.Live); } ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); uint initialSupply = _totalSupply(); require(initialSupply > 0); _pullAuthorizedTokens(thisErc20Token, tokensToRedeem); thisErc20Token.burn(tokensToRedeem); emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem); // Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor // margin account. uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply); uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage); s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin)); assert(s.longBalance >= 0); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); s._sendMargin(tokenMargin); } function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) { require( s.state == TDS.State.Live, "Contract must be Live to dispute" ); uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit)); uint sendInconsistencyRefund = s._pullSentMargin(depositMargin); require(depositMargin >= requiredDeposit); uint overpaymentRefund = depositMargin.sub(requiredDeposit); s.state = TDS.State.Disputed; s.endTime = s.currentTokenState.time; s.disputeInfo.disputedNav = s.nav; s.disputeInfo.deposit = requiredDeposit; // Store the default penalty in case the dispute pushes the sponsor into default. s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav); s._requestOraclePrice(s.endTime); // Add the two types of refunds: // 1. The refund for ETH sent if it was > depositMargin. // 2. The refund for depositMargin > requiredDeposit. s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund)); } function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) { // Remargin before allowing a withdrawal, but only if in the live state. if (s.state == TDS.State.Live) { s._remarginInternal(); } // Make sure either in Live or Settled after any necessary remargin. require(s.state == TDS.State.Live || s.state == TDS.State.Settled); // If the contract has been settled or is in prefunded state then can // withdraw up to full balance. If the contract is in live state then // must leave at least the required margin. Not allowed to withdraw in // other states. int withdrawableAmount; if (s.state == TDS.State.Settled) { withdrawableAmount = s.shortBalance; } else { // Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit. uint currentTime = s.currentTokenState.time; if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) { // We've passed the previous s.withdrawThrottle window. Start new one. s.withdrawThrottle.startTime = currentTime; s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit); } int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState)); int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal); // Take the smallest of the two withdrawal limits. withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw; // Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above // ternary is more explicit. s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount); } // Can only withdraw the allowed amount. require( withdrawableAmount >= _safeIntCast(amount), "Attempting to withdraw more than allowed" ); // Transfer amount - Note: important to `-=` before the send so that the // function can not be called multiple times while waiting for transfer // to return. s.shortBalance = s.shortBalance.sub(_safeIntCast(amount)); emit Withdrawal(s.fixedParameters.symbol, amount); s._sendMargin(amount); } function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) { // Right now, only confirming prices in the defaulted state. require(s.state == TDS.State.Defaulted); // Remargin on agreed upon price. s._settleAgreedPrice(); } function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) { s.externalAddresses.apDelegate = _apDelegate; } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) { require(s.state == TDS.State.Live); s.state = TDS.State.Emergency; s.endTime = s.currentTokenState.time; s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime); s._requestOraclePrice(s.endTime); } function _settle(TDS.Storage storage s) external { s._settleInternal(); } function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { // Returns any refund due to sending more margin than the argument indicated (should only be able to happen in // the ETH case). uint refund = s._pullSentMargin(marginForPurchase); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase)); // Send the accumulated refund. s._sendMargin(refund); } function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) { // Only allow the s.externalAddresses.sponsor to deposit margin. uint refund = s._pullSentMargin(marginToDeposit); s._depositInternal(marginToDeposit); // Send any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). s._sendMargin(refund); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function _calcNAV(TDS.Storage storage s) external view returns (int navNew) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) { (TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance(); newTokenValue = newTokenState.tokenPrice; } // Returns the expected balance of the short margin account using the latest available Price Feed price. function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) { (, newShortMarginBalance) = s._calcNewTokenStateAndBalance(); } function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) { (TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance(); // If the contract is in/will be moved to a settled state, the margin requirement will be 0. int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState); return newShortMarginBalance.sub(requiredMargin); } function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) { if (s.state == TDS.State.Settled) { // No margin needs to be maintained when the contract is settled. return 0; } return s._getRequiredMargin(s.currentTokenState); } function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) { TDS.State currentState = s.state; if (currentState == TDS.State.Settled) { return false; } // Technically we should also check if price will default the contract, but that isn't a normal flow of // operations that we want to simulate: we want to discourage the sponsor remargining into a default. (uint priceFeedTime, ) = s._getLatestPrice(); if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) { return false; } return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime); } function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); return (newTokenState.underlyingPrice, newTokenState.time); } function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance) { // TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted // so the logic can be written once and used twice. However, much of this was written post-audit, so it was // deemed preferable not to modify any state changing code that could potentially introduce new security // bugs. This should be done before the next contract audit. if (s.state == TDS.State.Settled) { // If the contract is Settled, just return the current contract state. return (s.currentTokenState, s.shortBalance); } // Grab the price feed pricetime. (uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice(); bool isContractLive = s.state == TDS.State.Live; bool isContractPostExpiry = priceFeedTime >= s.endTime; // If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values. if (isContractLive && priceFeedTime <= s.currentTokenState.time) { return (s.currentTokenState, s.shortBalance); } // Determine which previous price state to use when computing the new NAV. // If the contract is live, we use the reference for the linear return type or if the contract will immediately // move to expiry. bool shouldUseReferenceTokenState = isContractLive && (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry); TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState; // Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin. (uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ? (s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) : (priceFeedTime, priceFeedPrice); // Init the returned short balance to the current short balance. newShortMarginBalance = s.shortBalance; // Subtract the oracle fees from the short balance. newShortMarginBalance = isContractLive ? newShortMarginBalance.sub( _safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) : newShortMarginBalance; // Compute the new NAV newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime); int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance)); // If the contract is frozen or will move into expiry, we need to settle it, which means adding the default // penalty and dispute deposit if necessary. if (!isContractLive || isContractPostExpiry) { // Subtract default penalty (if necessary) from the short balance. bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState); if (inDefault) { int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty(); int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ? newShortMarginBalance : expectedDefaultPenalty; newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty); } // Add the dispute deposit to the short balance if necessary. if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) { int depositValue = _safeIntCast(s.disputeInfo.deposit); newShortMarginBalance = newShortMarginBalance.add(depositValue); } } } function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice) internal returns (int navNew) { int unitNav = _safeIntCast(startingTokenPrice); s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); // Starting NAV is always 0 in the TokenizedDerivative case. navNew = 0; } function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) { s._remarginInternal(); } function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) { if(address(s.externalAddresses.marginCurrency) == erc20Address) { uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this)); int totalBalances = s.shortBalance.add(s.longBalance); assert(totalBalances >= 0); uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit); require(withdrawableAmount >= amount); } IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal { // Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that // tokens fail to conform is that they do not return a bool from certain state-changing operations. This // contract was not designed to work with those tokens because of the additional complexity they would // introduce. s.externalAddresses.marginCurrency = IERC20(params.marginCurrency); s.externalAddresses.oracle = OracleInterface(params.oracle); s.externalAddresses.store = StoreInterface(params.store); s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed); s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator); // Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product. require(s.externalAddresses.oracle.isIdentifierSupported(params.product)); require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product)); s.externalAddresses.sponsor = params.sponsor; s.externalAddresses.admin = params.admin; } function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal { // Ensure only valid enum values are provided. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.returnType == TokenizedDerivativeParams.ReturnType.Linear); // Fee must be 0 if the returnType is linear. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0); // The default penalty must be less than the required margin. require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR); s.fixedParameters.returnType = params.returnType; s.fixedParameters.defaultPenalty = params.defaultPenalty; s.fixedParameters.product = params.product; s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR); s.fixedParameters.disputeDeposit = params.disputeDeposit; s.fixedParameters.supportedMove = params.supportedMove; s.fixedParameters.withdrawLimit = params.withdrawLimit; s.fixedParameters.creationTime = params.creationTime; s.fixedParameters.symbol = symbol; } // _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for // _remargin(). function _remarginInternal(TDS.Storage storage s) internal { // If the state is not live, remargining does not make sense. require(s.state == TDS.State.Live); (uint latestTime, int latestPrice) = s._getLatestPrice(); // Checks whether contract has ended. if (latestTime <= s.currentTokenState.time) { // If the price feed hasn't advanced, remargining should be a no-op. return; } // Save the penalty using the current state in case it needs to be used. int potentialPenaltyAmount = s._computeDefaultPenalty(); if (latestTime >= s.endTime) { s.state = TDS.State.Expired; emit Expired(s.fixedParameters.symbol, s.endTime); // Applies the same update a second time to effectively move the current state to the reference state. int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time); assert(recomputedNav == s.nav); uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime); // Save the precomputed default penalty in case the expiry price pushes the sponsor into default. s.defaultPenaltyAmount = potentialPenaltyAmount; // We have no idea what the price was, exactly at s.endTime, so we can't set // s.currentTokenState, or update the nav, or do anything. s._requestOraclePrice(s.endTime); s._payOracleFees(feeAmount); return; } uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime); // Update nav of contract. int navNew = s._computeNav(latestPrice, latestTime); // Update the balances of the contract. s._updateBalances(navNew); // Make sure contract has not moved into default. bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { s.state = TDS.State.Defaulted; s.defaultPenaltyAmount = potentialPenaltyAmount; s.endTime = latestTime; // Change end time to moment when default occurred. emit Default(s.fixedParameters.symbol, latestTime, s.nav); s._requestOraclePrice(latestTime); } s._payOracleFees(feeAmount); } function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) { s._remarginInternal(); // Verify that remargining didn't push the contract into expiry or default. require(s.state == TDS.State.Live); int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (purchasedNav < 0) { purchasedNav = 0; } // Ensures that requiredNav >= navSent. refund = navSent.sub(_safeUintCast(purchasedNav)); s.longBalance = s.longBalance.add(purchasedNav); ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); thisErc20Token.mint(msg.sender, tokensToPurchase); emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); // Make sure this still satisfies the margin requirement. require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState)); } function _depositInternal(TDS.Storage storage s, uint value) internal { // Make sure that we are in a "depositable" state. require(s.state == TDS.State.Live); s.shortBalance = s.shortBalance.add(_safeIntCast(value)); emit Deposited(s.fixedParameters.symbol, value); } function _settleInternal(TDS.Storage storage s) internal { TDS.State startingState = s.state; require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired || startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency); s._settleVerifiedPrice(); if (startingState == TDS.State.Disputed) { int depositValue = _safeIntCast(s.disputeInfo.deposit); if (s.nav != s.disputeInfo.disputedNav) { s.shortBalance = s.shortBalance.add(depositValue); } else { s.longBalance = s.longBalance.add(depositValue); } } } // Deducts the fees from the margin account. function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) { feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime); s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount)); // If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the // contract. } // Pays out the fees to the Oracle. function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal { if (feeAmount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { s.externalAddresses.store.payOracleFees.value(feeAmount)(); } else { require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount)); s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency)); } } function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal view returns (uint feeAmount) { // The profit from corruption is set as the max(longBalance, shortBalance). int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance; uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc)); // Ensure the fee returned can actually be paid by the short margin account. uint shortBalance = _safeUintCast(s.shortBalance); return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount; } function _computeNewTokenState(TDS.Storage storage s, TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime) internal view returns (TDS.TokenState memory newTokenState) { int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn( beginningTokenState.underlyingPrice, latestUnderlyingPrice); int tokenReturn = underlyingReturn.sub( _safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time)))); int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR); // In the compound case, don't allow the token price to go below 0. if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) { tokenMultiplier = 0; } int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier); newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime); } function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState) internal view returns (bool doesSatisfyRequirement) { return s._getRequiredMargin(tokenState) <= balance; } function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal { uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime); if (expectedTime == 0) { // The Oracle price is already available, settle the contract right away. s._settleInternal(); } } function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) { (latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); require(latestTime != 0); } function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) { navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime); } else { assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear); navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime); } } function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { s.referenceTokenState = s.currentTokenState; s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { // Only update the time - don't update the prices becuase all price changes are relative to the initial price. s.referenceTokenState.time = s.currentTokenState.time; s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) { // We're updating `last` based on what the Oracle has told us. assert(s.endTime == recomputeTime); s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } // Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all // of the settlement logic including assessing penalties and then moves the state to `Settled`. function _settleWithPrice(TDS.Storage storage s, int price) internal { // Remargin at whatever price we're using (verified or unverified). s._updateBalances(s._recomputeNav(price, s.endTime)); bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { int expectedDefaultPenalty = s._getDefaultPenalty(); int penalty = (s.shortBalance < expectedDefaultPenalty) ? s.shortBalance : expectedDefaultPenalty; s.shortBalance = s.shortBalance.sub(penalty); s.longBalance = s.longBalance.add(penalty); } s.state = TDS.State.Settled; emit Settled(s.fixedParameters.symbol, s.endTime, s.nav); } function _updateBalances(TDS.Storage storage s, int navNew) internal { // Compute difference -- Add the difference to owner and subtract // from counterparty. Then update nav state variable. int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance); s.nav = navNew; s.longBalance = s.longBalance.add(longDiff); s.shortBalance = s.shortBalance.sub(longDiff); } function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return s.defaultPenaltyAmount; } function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty); } function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState) internal view returns (int requiredMargin) { int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage()); int effectiveNotional; if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) { int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude); effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR); } else { int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply()); effectiveNotional = currentNav.mul(leverageMagnitude); } // Take the absolute value of the notional since a negative notional has similar risk properties to a positive // notional of the same size, and, therefore, requires the same margin. requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove); } function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) { if (address(s.externalAddresses.marginCurrency) == address(0x0)) { // Refund is any amount of ETH that was sent that was above the amount that was expected. // Note: SafeMath will force a revert if msg.value < expectedMargin. return msg.value.sub(expectedMargin); } else { // If we expect an ERC20 token, no ETH should be sent. require(msg.value == 0); _pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin); // There is never a refund in the ERC20 case since we use the argument to determine how much to "pull". return 0; } } function _sendMargin(TDS.Storage storage s, uint amount) internal { // There's no point in attempting a send if there's nothing to send. if (amount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { msg.sender.transfer(amount); } else { require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount)); } } function _settleAgreedPrice(TDS.Storage storage s) internal { int agreedPrice = s.currentTokenState.underlyingPrice; s._settleWithPrice(agreedPrice); } function _settleVerifiedPrice(TDS.Storage storage s) internal { int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime); s._settleWithPrice(oraclePrice); } function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private { // If nothing is being pulled, there's no point in calling a transfer. if (amountToPull > 0) { require(erc20.transferFrom(msg.sender, address(this), amountToPull)); } } // Gets the change in balance for the long side. // Note: there's a function for this because signage is tricky here, and it must be done the same everywhere. function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) { int newLongBalance = navNew; // Long balance cannot go below zero. if (newLongBalance < 0) { newLongBalance = 0; } longDiff = newLongBalance.sub(longBalance); // Cannot pull more margin from the short than is available. if (longDiff > shortBalance) { longDiff = shortBalance; } } function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) { int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice); navNew = navPreDivision.div(INT_FP_SCALING_FACTOR); // The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens // cannot be purchased or backed with less than their true value. if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) { navNew = navNew.add(1); } } function _totalSupply() private view returns (uint totalSupply) { ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); return thisErc20Token.totalSupply(); } function _takePercentage(uint value, uint percentage) private pure returns (uint result) { return value.mul(percentage).div(UINT_FP_SCALING_FACTOR); } function _takePercentage(int value, uint percentage) private pure returns (int result) { return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR); } function _takePercentage(int value, int percentage) private pure returns (int result) { return value.mul(percentage).div(INT_FP_SCALING_FACTOR); } function _absoluteValue(int value) private pure returns (int result) { return value < 0 ? value.mul(-1) : value; } function _safeIntCast(uint value) private pure returns (int result) { require(value <= INT_MAX); return int(value); } function _safeUintCast(int value) private pure returns (uint result) { require(value >= 0); return uint(value); } // Note that we can't have the symbol parameter be `indexed` due to: // TypeError: Indexed reference types cannot yet be used with ABIEncoderV2. // An event emitted when the NAV of the contract changes. event NavUpdated(string symbol, int newNav, int newTokenPrice); // An event emitted when the contract enters the Default state on a remargin. event Default(string symbol, uint defaultTime, int defaultNav); // An event emitted when the contract settles. event Settled(string symbol, uint settleTime, int finalNav); // An event emitted when the contract expires. event Expired(string symbol, uint expiryTime); // An event emitted when the contract's NAV is disputed by the sponsor. event Disputed(string symbol, uint timeDisputed, int navDisputed); // An event emitted when the contract enters emergency shutdown. event EmergencyShutdownTransition(string symbol, uint shutdownTime); // An event emitted when tokens are created. event TokensCreated(string symbol, uint numTokensCreated); // An event emitted when tokens are redeemed. event TokensRedeemed(string symbol, uint numTokensRedeemed); // An event emitted when margin currency is deposited. event Deposited(string symbol, uint amount); // An event emitted when margin currency is withdrawn. event Withdrawal(string symbol, uint amount); } // TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality. contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 { using TokenizedDerivativeUtils for TDS.Storage; // Note: these variables are to give ERC20 consumers information about the token. string public name; string public symbol; uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase TDS.Storage public derivativeStorage; constructor( TokenizedDerivativeParams.ConstructorParams memory params, string memory _name, string memory _symbol ) public { // Set token properties. name = _name; symbol = _symbol; // Initialize the contract. derivativeStorage._initialize(params, _symbol); } // Creates tokens with sent margin and returns additional margin. function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._createTokens(marginForPurchase, tokensToPurchase); } // Creates tokens with sent margin and deposits additional margin in short account. function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase); } // Redeems tokens for margin currency. function redeemTokens(uint tokensToRedeem) external { derivativeStorage._redeemTokens(tokensToRedeem); } // Triggers a price dispute for the most recent remargin time. function dispute(uint depositMargin) external payable { derivativeStorage._dispute(depositMargin); } // Withdraws `amount` from short margin account. function withdraw(uint amount) external { derivativeStorage._withdraw(amount); } // Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and // short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements. function remargin() external { derivativeStorage._remargin(); } // Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on // contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long // account. function acceptPriceAndSettle() external { derivativeStorage._acceptPriceAndSettle(); } // Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no // Delegate AP. function setApDelegate(address apDelegate) external { derivativeStorage._setApDelegate(apDelegate); } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function emergencyShutdown() external { derivativeStorage._emergencyShutdown(); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function calcNAV() external view returns (int navNew) { return derivativeStorage._calcNAV(); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function calcTokenValue() external view returns (int newTokenValue) { return derivativeStorage._calcTokenValue(); } // Returns the expected balance of the short margin account using the latest available Price Feed price. function calcShortMarginBalance() external view returns (int newShortMarginBalance) { return derivativeStorage._calcShortMarginBalance(); } // Returns the expected short margin in excess of the margin requirement using the latest available Price Feed // price. Value will be negative if the short margin is expected to be below the margin requirement. function calcExcessMargin() external view returns (int excessMargin) { return derivativeStorage._calcExcessMargin(); } // Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the // latest available Price Feed price. function getCurrentRequiredMargin() external view returns (int requiredMargin) { return derivativeStorage._getCurrentRequiredMargin(); } // Returns whether the contract can be settled, i.e., is it valid to call settle() now. function canBeSettled() external view returns (bool canContractBeSettled) { return derivativeStorage._canBeSettled(); } // Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if // the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled. // Reverts if no Oracle price is available but an Oracle price is required. function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) { return derivativeStorage._getUpdatedUnderlyingPrice(); } // When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract // into the `Settled` state. function settle() external { derivativeStorage._settle(); } // Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call) // to the short account. function deposit(uint amountToDeposit) external payable { derivativeStorage._deposit(amountToDeposit); } // Allows the sponsor to withdraw any ERC20 balance that is not the margin token. function withdrawUnexpectedErc20(address erc20Address, uint amount) external { derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount); } // ExpandedIERC20 methods. modifier onlyThis { require(msg.sender == address(this)); _; } // Only allow calls from this contract or its libraries to burn tokens. function burn(uint value) external onlyThis { // Only allow calls from this contract or its libraries to burn tokens. _burn(msg.sender, value); } // Only allow calls from this contract or its libraries to mint tokens. function mint(address to, uint256 value) external onlyThis { _mint(to, value); } // These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events // here as well. event NavUpdated(string symbol, int newNav, int newTokenPrice); event Default(string symbol, uint defaultTime, int defaultNav); event Settled(string symbol, uint settleTime, int finalNav); event Expired(string symbol, uint expiryTime); event Disputed(string symbol, uint timeDisputed, int navDisputed); event EmergencyShutdownTransition(string symbol, uint shutdownTime); event TokensCreated(string symbol, uint numTokensCreated); event TokensRedeemed(string symbol, uint numTokensRedeemed); event Deposited(string symbol, uint amount); event Withdrawal(string symbol, uint amount); } contract TokenizedDerivativeCreator is ContractCreator, Testable { struct Params { uint defaultPenalty; // Percentage of mergin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of mergin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of shortBalance * 10^18 TokenizedDerivativeParams.ReturnType returnType; uint startingUnderlyingPrice; string name; string symbol; } AddressWhitelist public sponsorWhitelist; AddressWhitelist public returnCalculatorWhitelist; AddressWhitelist public marginCurrencyWhitelist; constructor( address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress, address _sponsorWhitelist, address _returnCalculatorWhitelist, address _marginCurrencyWhitelist, bool _isTest ) public ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress) Testable(_isTest) { sponsorWhitelist = AddressWhitelist(_sponsorWhitelist); returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist); marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist); } function createTokenizedDerivative(Params memory params) public returns (address derivativeAddress) { TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol); address[] memory parties = new address[](1); parties[0] = msg.sender; _registerContract(parties, address(derivative)); return address(derivative); } // Converts createTokenizedDerivative params to TokenizedDerivative constructor params. function _convertParams(Params memory params) private view returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams) { // Copy and verify externally provided variables. require(sponsorWhitelist.isOnWhitelist(msg.sender)); constructorParams.sponsor = msg.sender; require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator)); constructorParams.returnCalculator = params.returnCalculator; require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency)); constructorParams.marginCurrency = params.marginCurrency; constructorParams.defaultPenalty = params.defaultPenalty; constructorParams.supportedMove = params.supportedMove; constructorParams.product = params.product; constructorParams.fixedYearlyFee = params.fixedYearlyFee; constructorParams.disputeDeposit = params.disputeDeposit; constructorParams.startingTokenPrice = params.startingTokenPrice; constructorParams.expiry = params.expiry; constructorParams.withdrawLimit = params.withdrawLimit; constructorParams.returnType = params.returnType; constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice; // Copy internal variables. constructorParams.priceFeed = priceFeedAddress; constructorParams.oracle = oracleAddress; constructorParams.store = storeAddress; constructorParams.admin = oracleAddress; constructorParams.creationTime = getCurrentTime(); } }
Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled. Reverts if no Oracle price is available but an Oracle price is required.
function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) { return derivativeStorage._getUpdatedUnderlyingPrice(); }
972,402
[ 1, 1356, 326, 3526, 6808, 6205, 716, 1703, 1399, 316, 326, 7029, 2590, 5721, 18, 2597, 903, 506, 279, 6205, 4746, 6205, 309, 326, 6835, 353, 21559, 471, 903, 7232, 21559, 16, 578, 392, 28544, 6205, 309, 326, 6835, 353, 26319, 1259, 19, 21071, 358, 506, 26319, 1259, 18, 868, 31537, 309, 1158, 28544, 6205, 353, 2319, 1496, 392, 28544, 6205, 353, 1931, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 7381, 14655, 6291, 5147, 1435, 3903, 1476, 1135, 261, 474, 6808, 5147, 16, 2254, 813, 13, 288, 203, 3639, 327, 16417, 3245, 6315, 588, 7381, 14655, 6291, 5147, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x8413428357b3e3842666c36502c3ddef4eb3fc74 //Contract name: GECToken //Balance: 0 Ether //Verification Date: 8/24/2017 //Transacion Count: 0 // CODE STARTS HERE pragma solidity 0.4.11; contract ERC20 { function totalSupply() constant returns (uint256 totalSupply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _recipient, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _recipient, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _recipient, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is ERC20 { uint256 public totalSupply; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; modifier when_can_transfer(address _from, uint256 _value) { if (balances[_from] >= _value) _; } modifier when_can_receive(address _recipient, uint256 _value) { if (balances[_recipient] + _value > balances[_recipient]) _; } modifier when_is_allowed(address _from, address _delegate, uint256 _value) { if (allowed[_from][_delegate] >= _value) _; } function transfer(address _recipient, uint256 _value) when_can_transfer(msg.sender, _value) when_can_receive(_recipient, _value) returns (bool o_success) { balances[msg.sender] -= _value; balances[_recipient] += _value; Transfer(msg.sender, _recipient, _value); return true; } function transferFrom(address _from, address _recipient, uint256 _value) when_can_transfer(_from, _value) when_can_receive(_recipient, _value) when_is_allowed(_from, msg.sender, _value) returns (bool o_success) { allowed[_from][msg.sender] -= _value; balances[_from] -= _value; balances[_recipient] += _value; Transfer(_from, _recipient, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool o_success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 o_remaining) { return allowed[_owner][_spender]; } } contract GECToken is StandardToken { //FIELDS string public name = "GECoin"; string public symbol = "GEC"; uint public decimals = 3; //INITIALIZATION address public minter; //address that able to mint new tokens uint public icoEndTime; uint illiquidBalance_amount; mapping (uint => address) illiquidBalance_index; mapping (address => uint) public illiquidBalance; //Balance of 'Frozen funds' // called by crowdsale contract modifier only_minter { if (msg.sender != minter) throw; _; } // Token can be transferred immediately after crowdsale. modifier when_transferable { if (now <= icoEndTime) throw; _; } // Can only be called if the `crowdfunder` is allowed to mint tokens. Any // time before `endMintingTime`. modifier when_mintable { if (now > icoEndTime + 10 days) throw; _; } // Initialization contract assigns address of crowdfund contract and end time. function GECToken (address _minter, uint _icoEndTime) { minter = _minter; icoEndTime = _icoEndTime; } // Create new tokens when called by the crowdfund contract. // Only callable before the end time. function createToken(address _recipient, uint _value) when_mintable only_minter returns (bool o_success) { balances[_recipient] += _value; totalSupply += _value; return true; } // Create an illiquidBalance which cannot be traded until admin make it liquid. // Can only be called by crowdfund contract before the end time. function createIlliquidToken(address _recipient, uint _value) when_mintable only_minter returns (bool o_success) { illiquidBalance_index[illiquidBalance_amount] = _recipient; illiquidBalance[_recipient] += _value; illiquidBalance_amount++; totalSupply += _value; return true; } // Make sender's illiquid balance liquid when called after lockout period. function makeLiquid() only_minter { for (uint i=0; i<illiquidBalance_amount; i++) { address investor = illiquidBalance_index[i]; balances[investor] += illiquidBalance[investor]; illiquidBalance[investor] = 0; } } // Transfer amount of tokens from sender account to recipient. // Only callable after the crowd fund end date. function transfer(address _recipient, uint _amount) when_transferable returns (bool o_success) { return super.transfer(_recipient, _amount); } // Transfer amount of tokens from a specified address to a recipient. // Only callable after the crowd fund end date. function transferFrom(address _from, address _recipient, uint _amount) when_transferable returns (bool o_success) { return super.transferFrom(_from, _recipient, _amount); } }
Create an illiquidBalance which cannot be traded until admin make it liquid. Can only be called by crowdfund contract before the end time.
function createIlliquidToken(address _recipient, uint _value) when_mintable only_minter returns (bool o_success) { illiquidBalance_index[illiquidBalance_amount] = _recipient; illiquidBalance[_recipient] += _value; illiquidBalance_amount++; totalSupply += _value; return true; }
5,395,360
[ 1, 1684, 392, 14254, 549, 26595, 13937, 1492, 2780, 506, 1284, 785, 3180, 3981, 1221, 518, 4501, 26595, 18, 4480, 1338, 506, 2566, 635, 276, 492, 2180, 1074, 6835, 1865, 326, 679, 813, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 752, 45, 80, 549, 26595, 1345, 12, 2867, 389, 20367, 16, 2254, 389, 1132, 13, 203, 202, 202, 13723, 67, 81, 474, 429, 203, 202, 202, 3700, 67, 1154, 387, 203, 202, 202, 6154, 261, 6430, 320, 67, 4768, 13, 203, 202, 95, 203, 202, 202, 16607, 26595, 13937, 67, 1615, 63, 16607, 26595, 13937, 67, 8949, 65, 273, 389, 20367, 31, 203, 202, 202, 16607, 26595, 13937, 63, 67, 20367, 65, 1011, 389, 1132, 31, 203, 202, 202, 16607, 26595, 13937, 67, 8949, 9904, 31, 203, 203, 202, 202, 4963, 3088, 1283, 1011, 389, 1132, 31, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x2c64Ee62fA9DAf74D4F77169EeFC5801a279FBda/sources/contracts/edit.sol
Calculate reward based on the provided percentage
uint256 rewardAmount = (item.reward * percentage) / 100;
5,602,224
[ 1, 8695, 19890, 2511, 603, 326, 2112, 11622, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 19890, 6275, 273, 261, 1726, 18, 266, 2913, 380, 11622, 13, 342, 2130, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 /// @title FOMO Nouns Settlement Contract /// @author forager pragma solidity 0.8.9; import { INounsAuctionHouse } from './interfaces/INounsAuctionHouse.sol'; contract NounSettlement { address payable public fomoExecutor; address payable public immutable nounsDaoTreasury; address public immutable fomoMultisig; INounsAuctionHouse public immutable auctionHouse; uint256 public maxPriorityFee = 40 * 10**9; // Prevents malicious actor burning all the ETH on gas uint256 private immutable OVERHEAD_GAS = 21000; // Handles gas outside gasleft checks, rounded up from ~20,254 in testing constructor(address _fomoExecutor, address _nounsDaoTreasury, address _nounsAuctionHouseAddress, address _fomoMultisig) { fomoExecutor = payable(_fomoExecutor); nounsDaoTreasury = payable(_nounsDaoTreasury); fomoMultisig = _fomoMultisig; auctionHouse = INounsAuctionHouse(_nounsAuctionHouseAddress); } /** Events for key actions or parameter updates */ /// @notice Contract funds withdrawn to the Nouns Treasury event FundsPulled(address _to, uint256 _amount); /// @notice FOMO Executor EOA moved to a new address event ExecutorChanged(address _newExecutor); /// @notice Maximum priority fee for refunds updated event MaxPriorityFeeChanged(uint256 _newMaxPriorityFee); /** Custom modifiers to handle access and refund */ modifier onlyMultisig() { require(msg.sender == fomoMultisig, "Only callable by FOMO Multsig"); _; } modifier onlyFOMO() { require(msg.sender == fomoExecutor, "Only callable by FOMO Nouns executor"); _; } modifier refundGas() { // Executor must be EOA uint256 startGas = gasleft(); require(tx.gasprice <= block.basefee + maxPriorityFee, "Gas price above current reasonable limit"); _; uint256 endGas = gasleft(); uint256 totalGasCost = tx.gasprice * (startGas - endGas + OVERHEAD_GAS); fomoExecutor.transfer(totalGasCost); } /** Fund management to allow donations and liquidation */ /// @notice Donate funds to cover auction settlement gas fees function donateFunds() external payable { } receive() external payable { } fallback() external payable { } /// @notice Pull all funds from contract into the Nouns DAO Treasury function pullFunds() external onlyMultisig { uint256 balance = address(this).balance; (bool sent, ) = nounsDaoTreasury.call{value: balance}(""); require(sent, "Funds removal failed."); emit FundsPulled(nounsDaoTreasury, balance); } /** Change addresses or limits for the contract execution */ /// @notice Change address for the FOMO Executor EOA that can request gas refunds function changeExecutorAddress(address _newFomoExecutor) external onlyMultisig { fomoExecutor = payable(_newFomoExecutor); emit ExecutorChanged(fomoExecutor); } /// @notice Update the maximum allowed priority fee (in wei) for refunds function changeMaxPriorityFee(uint256 _newMaxPriorityFee) external onlyMultisig { maxPriorityFee = _newMaxPriorityFee; emit MaxPriorityFeeChanged(maxPriorityFee); } /** Settle the Auction & Mint the Desired Nouns */ /// @notice Settle auction ensuring desired hash is used to generate the new Noun function settleAuction(bytes32 _desiredHash) public { bytes32 lastHash = blockhash(block.number - 1); // Only settle if desired Noun would be minted require(lastHash == _desiredHash, "Prior blockhash did not match intended hash"); auctionHouse.settleCurrentAndCreateNewAuction(); } /// @notice Settle auction, as with settleAuction, AND refund gas to caller function settleAuctionWithRefund(bytes32 _desiredHash) external refundGas onlyFOMO { settleAuction(_desiredHash); } } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for Noun Auction Houses /********************************* * β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ * * β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ * * β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘ * * β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–ˆβ–ˆβ–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘ * * β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘ * * β–‘β–‘β–ˆβ–ˆβ–‘β–‘β–ˆβ–ˆβ–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–ˆβ–ˆβ–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘ * * β–‘β–‘β–ˆβ–ˆβ–‘β–‘β–ˆβ–ˆβ–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–ˆβ–ˆβ–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘ * * β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘ * * β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ * * β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ * *********************************/ pragma solidity ^0.8.6; interface INounsAuctionHouse { struct Auction { // ID for the Noun (ERC721 token ID) uint256 nounId; // The current highest bid amount uint256 amount; // The time that the auction started uint256 startTime; // The time that the auction is scheduled to end uint256 endTime; // The address of the current highest bid address payable bidder; // Whether or not the auction has been settled bool settled; } event AuctionCreated(uint256 indexed nounId, uint256 startTime, uint256 endTime); event AuctionBid(uint256 indexed nounId, address sender, uint256 value, bool extended); event AuctionExtended(uint256 indexed nounId, uint256 endTime); event AuctionSettled(uint256 indexed nounId, address winner, uint256 amount); event AuctionTimeBufferUpdated(uint256 timeBuffer); event AuctionReservePriceUpdated(uint256 reservePrice); event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage); function settleAuction() external; function settleCurrentAndCreateNewAuction() external; function createBid(uint256 nounId) external payable; function pause() external; function unpause() external; function setTimeBuffer(uint256 timeBuffer) external; function setReservePrice(uint256 reservePrice) external; function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage) external; }
Executor must be EOA
modifier refundGas() {
340,673
[ 1, 6325, 1297, 506, 512, 28202, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 16255, 27998, 1435, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-01-31 */ pragma solidity ^0.6.6; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() public { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } /** * @title A trusted proxy for updating where current answers are read from * @notice This contract provides a consistent address for the * CurrentAnwerInterface but delegates where it reads from to the owner, who is * trusted to update it. */ contract AggregatorProxy is AggregatorV2V3Interface, Owned { struct Phase { uint16 id; AggregatorV2V3Interface aggregator; } Phase private currentPhase; AggregatorV2V3Interface public proposedAggregator; mapping(uint16 => AggregatorV2V3Interface) public phaseAggregators; uint256 constant private PHASE_OFFSET = 64; uint256 constant private PHASE_SIZE = 16; uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1; constructor(address _aggregator) public Owned() { setAggregator(_aggregator); } /** * @notice Reads the current answer from aggregator delegated to. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view virtual override returns (int256 answer) { return currentPhase.aggregator.latestAnswer(); } /** * @notice Reads the last updated height from aggregator delegated to. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view virtual override returns (uint256 updatedAt) { return currentPhase.aggregator.latestTimestamp(); } /** * @notice get past rounds answers * @param _roundId the answer number to retrieve the answer for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer(uint256 _roundId) public view virtual override returns (int256 answer) { if (_roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); AggregatorV2V3Interface aggregator = phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getAnswer(aggregatorRoundId); } /** * @notice get block timestamp when an answer was last updated * @param _roundId the answer number to retrieve the updated timestamp for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp(uint256 _roundId) public view virtual override returns (uint256 updatedAt) { if (_roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); AggregatorV2V3Interface aggregator = phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getTimestamp(aggregatorRoundId); } /** * @notice get the latest completed round where the answer was updated. This * ID includes the proxy's phase, to make sure round IDs increase even when * switching to a newly deployed aggregator. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view virtual override returns (uint256 roundId) { Phase memory phase = currentPhase; // cache storage reads return addPhase(phase.id, uint64(phase.aggregator.latestRound())); } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 ansIn ) = phaseAggregators[phaseId].getRoundData(aggregatorRoundId); return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, phaseId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Phase memory current = currentPhase; // cache storage reads ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 ansIn ) = current.aggregator.latestRoundData(); return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, current.id); } /** * @notice Used if an aggregator contract has been proposed. * @param _roundId the round ID to retrieve the round data for * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedGetRoundData(uint80 _roundId) public view virtual hasProposal() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return proposedAggregator.getRoundData(_roundId); } /** * @notice Used if an aggregator contract has been proposed. * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedLatestRoundData() public view virtual hasProposal() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return proposedAggregator.latestRoundData(); } /** * @notice returns the current phase's aggregator address. */ function aggregator() external view returns (address) { return address(currentPhase.aggregator); } /** * @notice returns the current phase's ID. */ function phaseId() external view returns (uint16) { return currentPhase.id; } /** * @notice represents the number of decimals the aggregator responses represent. */ function decimals() external view override returns (uint8) { return currentPhase.aggregator.decimals(); } /** * @notice the version number representing the type of aggregator the proxy * points to. */ function version() external view override returns (uint256) { return currentPhase.aggregator.version(); } /** * @notice returns the description of the aggregator the proxy points to. */ function description() external view override returns (string memory) { return currentPhase.aggregator.description(); } /** * @notice Allows the owner to propose a new address for the aggregator * @param _aggregator The new address for the aggregator contract */ function proposeAggregator(address _aggregator) external onlyOwner() { proposedAggregator = AggregatorV2V3Interface(_aggregator); } /** * @notice Allows the owner to confirm and change the address * to the proposed aggregator * @dev Reverts if the given address doesn't match what was previously * proposed * @param _aggregator The new address for the aggregator contract */ function confirmAggregator(address _aggregator) external onlyOwner() { require(_aggregator == address(proposedAggregator), "Invalid proposed aggregator"); delete proposedAggregator; setAggregator(_aggregator); } /* * Internal */ function setAggregator(address _aggregator) internal { uint16 id = currentPhase.id + 1; currentPhase = Phase(id, AggregatorV2V3Interface(_aggregator)); phaseAggregators[id] = AggregatorV2V3Interface(_aggregator); } function addPhase( uint16 _phase, uint64 _originalId ) internal view returns (uint80) { return uint80(uint256(_phase) << PHASE_OFFSET | _originalId); } function parseIds( uint256 _roundId ) internal view returns (uint16, uint64) { uint16 phaseId = uint16(_roundId >> PHASE_OFFSET); uint64 aggregatorRoundId = uint64(_roundId); return (phaseId, aggregatorRoundId); } function addPhaseIds( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound, uint16 phaseId ) internal view returns (uint80, int256, uint256, uint256, uint80) { return ( addPhase(phaseId, uint64(roundId)), answer, startedAt, updatedAt, addPhase(phaseId, uint64(answeredInRound)) ); } /* * Modifiers */ modifier hasProposal() { require(address(proposedAggregator) != address(0), "No proposed aggregator present"); _; } } 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; } } 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. */ 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; } } interface IEBOP20 is IERC20 { //constructor(string memory name_, string memory symbol_) public ERC20(name_, symbol_) /* Skeleton EBOP20 implementation. not useable*/ function bet(int256 latestPrice, uint256 amount) external virtual returns (uint256, uint256); function unlockAndPayExpirer(uint256 lockValue , uint256 purchaseValue, address expirer) external virtual returns (bool); function payout(uint256 lockValue,uint256 purchaseValue, address sender, address buyer) external virtual returns (bool); } /** * @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 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 { } } contract BIOPToken is ERC20 { using SafeMath for uint256; address public binaryOptions = 0x0000000000000000000000000000000000000000; address public gov; address public owner; uint256 public earlyClaimsAvailable = 450000000000000000000000000000; uint256 public totalClaimsAvailable = 750000000000000000000000000000; bool public earlyClaims = true; bool public binaryOptionsSet = false; constructor(string memory name_, string memory symbol_) public ERC20(name_, symbol_) { owner = msg.sender; } modifier onlyBinaryOptions() { require(binaryOptions == msg.sender, "Ownable: caller is not the Binary Options Contract"); _; } modifier onlyOwner() { require(binaryOptions == msg.sender, "Ownable: caller is not the owner"); _; } function updateEarlyClaim(uint256 amount) external onlyBinaryOptions { require(totalClaimsAvailable.sub(amount) >= 0, "insufficent claims available"); if (earlyClaims) { earlyClaimsAvailable = earlyClaimsAvailable.sub(amount); _mint(tx.origin, amount); if (earlyClaimsAvailable <= 0) { earlyClaims = false; } } else { updateClaim(amount.div(4)); } } function updateClaim( uint256 amount) internal { require(totalClaimsAvailable.sub(amount) >= 0, "insufficent claims available"); totalClaimsAvailable.sub(amount); _mint(tx.origin, amount); } function setupBinaryOptions(address payable options_) external { require(binaryOptionsSet != true, "binary options is already set"); binaryOptions = options_; } function setupGovernance(address payable gov_) external onlyOwner { _mint(owner, 100000000000000000000000000000); _mint(gov_, 450000000000000000000000000000); owner = 0x0000000000000000000000000000000000000000; } } /** * @title Power function by Bancor * @dev https://github.com/bancorprotocol/contracts * * Modified from the original by Slava Balasanov & Tarrence van As * * Split Power.sol out from BancorFormula.sol * https://github.com/bancorprotocol/contracts/blob/c9adc95e82fdfb3a0ada102514beb8ae00147f5d/solidity/contracts/converter/BancorFormula.sol * * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; * and to You under the Apache License, Version 2.0. " */ contract Power { string public version = "0.3"; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** The values below depend on MAX_PRECISION. If you choose to change it: Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below. */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** The values below depend on MIN_PRECISION and MAX_PRECISION. If you choose to change either one of them: Apply the same change in file 'PrintFunctionBancorFormula.py', run it and paste the results below. */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power( uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD ) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM, "baseN exceeds max value."); require(_baseN >= _baseD, "Bases < 1 are not supported."); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 _x) internal pure returns (uint256) { uint256 res = 0; uint256 x = _x; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; uint256 n = _n; if (n < 256) { // At most 8 iterations while (n > 1) { n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (n >= (ONE << s)) { n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; assert(false); return 0; } /* solhint-disable */ /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; return res; } /* solhint-enable */ } /** * @title Bancor formula by Bancor * * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; * and to You under the Apache License, Version 2.0. " */ contract BancorFormula is Power { using SafeMath for uint256; uint32 private constant MAX_RESERVE_RATIO = 1000000; /** * @dev given a continuous token supply, reserve token balance, reserve ratio, and a deposit amount (in the reserve token), * calculates the return for a given conversion (in the continuous token) * * Formula: * Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / MAX_RESERVE_RATIO) - 1) * * @param _supply continuous token total supply * @param _reserveBalance total reserve token balance * @param _reserveRatio reserve ratio, represented in ppm, 1-1000000 * @param _depositAmount deposit amount, in reserve token * * @return purchase return amount */ function calculatePurchaseReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO, "Invalid inputs."); // special case for 0 deposit amount if (_depositAmount == 0) { return 0; } // special case if the ratio = 100% if (_reserveRatio == MAX_RESERVE_RATIO) { return _supply.mul(_depositAmount).div(_reserveBalance); } uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_reserveBalance); (result, precision) = power( baseN, _reserveBalance, _reserveRatio, MAX_RESERVE_RATIO ); uint256 newTokenSupply = _supply.mul(result) >> precision; return newTokenSupply.sub(_supply); } /** * @dev given a continuous token supply, reserve token balance, reserve ratio and a sell amount (in the continuous token), * calculates the return for a given conversion (in the reserve token) * * Formula: * Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / MAX_RESERVE_RATIO))) * * @param _supply continuous token total supply * @param _reserveBalance total reserve token balance * @param _reserveRatio constant reserve ratio, represented in ppm, 1-1000000 * @param _sellAmount sell amount, in the continuous token itself * * @return sale return amount */ function calculateSaleReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO && _sellAmount <= _supply, "Invalid inputs."); // special case for 0 sell amount if (_sellAmount == 0) { return 0; } // special case for selling the entire supply if (_sellAmount == _supply) { return _reserveBalance; } // special case if the ratio = 100% if (_reserveRatio == MAX_RESERVE_RATIO) { return _reserveBalance.mul(_sellAmount).div(_supply); } uint256 result; uint8 precision; uint256 baseD = _supply.sub(_sellAmount); (result, precision) = power( _supply, baseD, MAX_RESERVE_RATIO, _reserveRatio ); uint256 oldBalance = _reserveBalance.mul(result); uint256 newBalance = _reserveBalance << precision; return oldBalance.sub(newBalance).div(result); } } interface IBondingCurve { /** * @dev Given a reserve token amount, calculates the amount of continuous tokens returned. */ function getContinuousMintReward(uint _reserveTokenAmount) external view returns (uint); /** * @dev Given a continuous token amount, calculates the amount of reserve tokens returned. */ function getContinuousBurnRefund(uint _continuousTokenAmount) external view returns (uint); } abstract contract BancorBondingCurve is IBondingCurve, BancorFormula { /* reserve ratio, represented in ppm, 1-1000000 1/3 corresponds to y= multiple * x^2 1/2 corresponds to y= multiple * x 2/3 corresponds to y= multiple * x^1/2 */ uint32 public reserveRatio; constructor(uint32 _reserveRatio) public { reserveRatio = _reserveRatio; } function getContinuousMintReward(uint _reserveTokenAmount) public override view returns (uint) { return calculatePurchaseReturn(continuousSupply(), reserveBalance(), reserveRatio, _reserveTokenAmount); } function getContinuousBurnRefund(uint _continuousTokenAmount) public override view returns (uint) { return calculateSaleReturn(continuousSupply(), reserveBalance(), reserveRatio, _continuousTokenAmount); } /** * @dev Abstract method that returns continuous token supply */ function continuousSupply() public virtual view returns (uint); /** * @dev Abstract method that returns reserve token balance */ function reserveBalance() public virtual view returns (uint); } contract BIOPTokenV3 is BancorBondingCurve, ERC20 { using SafeMath for uint256; address public bO = 0x0000000000000000000000000000000000000000;//binary options address payable gov = 0x0000000000000000000000000000000000000000; address payable owner; address public v2; uint256 lEnd;//launch end uint256 public tCA = 750000000000000000000000000000;//total claims available uint256 public tbca = 400000000000000000000000000000;//total bonding curve available bool public binaryOptionsSet = false; uint256 public soldAmount = 0; uint256 public buyFee = 2;//10th of percent uint256 public sellFee = 0;//10th of percent constructor(string memory name_, string memory symbol_, address v2_, uint32 _reserveRatio) public ERC20(name_, symbol_) BancorBondingCurve(_reserveRatio) { owner = msg.sender; v2 = v2_; lEnd = block.timestamp + 3 days; _mint(msg.sender, 100000); soldAmount = 100000; } modifier onlyBinaryOptions() { require(bO == msg.sender, "Ownable: caller is not the Binary Options Contract"); _; } modifier onlyGov() { if (gov == 0x0000000000000000000000000000000000000000) { require(owner == msg.sender, "Ownable: caller is not the owner"); } else { require(gov == msg.sender, "Ownable: caller is not the owner"); } _; } /** * @dev a one time function to setup governance * @param g_ the new governance address */ function transferGovernance(address payable g_) external onlyGov { require(gov == 0x0000000000000000000000000000000000000000); require(g_ != 0x0000000000000000000000000000000000000000); gov = g_; } /** * @dev set the fee users pay in ETH to buy BIOP from the bonding curve * @param newFee_ the new fee (in tenth percent) for buying on the curve */ function updateBuyFee(uint256 newFee_) external onlyGov { require(newFee_ > 0 && newFee_ < 40, "invalid fee"); buyFee = newFee_; } /** * @dev set the fee users pay in ETH to sell BIOP to the bonding curve * @param newFee_ the new fee (in tenth percent) for selling on the curve **/ function updateSellFee(uint256 newFee_) external onlyGov { require(newFee_ > 0 && newFee_ < 40, "invalid fee"); sellFee = newFee_; } /** * @dev called by the binary options contract to update a users Reward claim * @param amount the amount in BIOP to add to this users pending claims **/ function updateEarlyClaim(uint256 amount) external onlyBinaryOptions { require(tCA.sub(amount) >= 0, "insufficent claims available"); if (lEnd < block.timestamp) { tCA = tCA.sub(amount); _mint(tx.origin, amount.mul(4)); } else { tCA.sub(amount); _mint(tx.origin, amount); } } /** * @notice one time function used at deployment to configure the connected binary options contract * @param options_ the address of the binary options contract */ function setupBinaryOptions(address payable options_) external { require(binaryOptionsSet != true, "binary options is already set"); bO = options_; binaryOptionsSet = true; } /** * @dev one time swap of v2 to v3 tokens * @notice all v2 tokens will be swapped to v3. This cannot be undone */ function swapv2v3() external { BIOPToken b2 = BIOPToken(v2); uint256 balance = b2.balanceOf(msg.sender); require(balance >= 0, "insufficent biopv2 balance"); require(b2.transferFrom(msg.sender, address(this), balance), "staking failed"); _mint(msg.sender, balance); } //bonding curve functions /** * @dev method that returns BIOP amount sold by curve */ function continuousSupply() public override view returns (uint) { return soldAmount; } /** * @dev method that returns curves ETH (reserve) balance */ function reserveBalance() public override view returns (uint) { return address(this).balance; } /** * @notice purchase BIOP from the bonding curve. the amount you get is based on the amount in the pool and the amount of eth u send. */ function buy() public payable { uint256 purchaseAmount = msg.value; if (buyFee > 0) { uint256 fee = purchaseAmount.div(buyFee).div(100); if (gov == 0x0000000000000000000000000000000000000000) { require(owner.send(fee), "buy fee transfer failed"); } else { require(gov.send(fee), "buy fee transfer failed"); } purchaseAmount = purchaseAmount.sub(fee); } uint rewardAmount = getContinuousMintReward(purchaseAmount); require(soldAmount.add(rewardAmount) <= tbca, "maximum curve minted"); _mint(msg.sender, rewardAmount); soldAmount = soldAmount.add(rewardAmount); } /** * @notice sell BIOP to the bonding curve * @param amount the amount of BIOP to sell */ function sell(uint256 amount) public returns (uint256){ require(balanceOf(msg.sender) >= amount, "insufficent BIOP balance"); uint256 ethToSend = getContinuousBurnRefund(amount); if (sellFee > 0) { uint256 fee = ethToSend.div(buyFee).div(100); if (gov == 0x0000000000000000000000000000000000000000) { require(owner.send(fee), "buy fee transfer failed"); } else { require(gov.send(fee), "buy fee transfer failed"); } ethToSend = ethToSend.sub(fee); } soldAmount = soldAmount.sub(amount); _burn(msg.sender, amount); require(msg.sender.send(ethToSend), "transfer failed"); return ethToSend; } } interface IRCD { /** * @notice Returns the rate to pay out for a given amount * @param amount the bet amount to calc a payout for * @param maxAvailable the total pooled ETH unlocked and available to bet * @param oldPrice the previous price of the underlying * @param newPrice the current price of the underlying * @return profit total possible profit amount */ function rate(uint256 amount, uint256 maxAvailable, uint256 oldPrice, uint256 newPrice) external view returns (uint256); } contract RateCalc is IRCD { using SafeMath for uint256; /** * @notice Calculates maximum option buyer profit * @param amount Option amount * @param maxAvailable the total pooled ETH unlocked and available to bet * @param oldPrice the previous price of the underlying * @param newPrice the current price of the underlying * @return profit total possible profit amount */ function rate(uint256 amount, uint256 maxAvailable, uint256 oldPrice, uint256 newPrice) external view override returns (uint256) { require(amount <= maxAvailable, "greater then pool funds available"); uint256 oneTenth = amount.div(10); uint256 halfMax = maxAvailable.div(2); if (amount > halfMax) { return amount.mul(2).add(oneTenth).add(oneTenth); } else { if(oneTenth > 0) { return amount.mul(2).sub(oneTenth); } else { uint256 oneThird = amount.div(4); require(oneThird > 0, "invalid bet amount"); return amount.mul(2).sub(oneThird); } } } } /** * @title Binary Options Eth Pool * @author github.com/BIOPset * @dev Pool ETH Tokens and use it for optionss * Biop */ contract BinaryOptions is ERC20 { using SafeMath for uint256; address payable devFund; address payable owner; address public biop; address public defaultRCAddress;//address of default rate calculator mapping(address=>uint256) public nW; //next withdraw (used for pool lock time) mapping(address=>address) public ePairs;//enabled pairs. price provider mapped to rate calc mapping(address=>int256) public pLP; //pair last price. the last recorded price for this pair mapping(address=>uint256) public lW;//last withdraw.used for rewards calc mapping(address=>uint256) private pClaims;//pending claims mapping(address=>uint256) public iAL;//interchange at last claim mapping(address=>uint256) public lST;//last stake time //erc20 pools stuff mapping(address=>bool) public ePools;//enabled pools mapping(address=>uint256) public altLockedAmount; uint256 public minT;//min time uint256 public maxT;//max time address public defaultPair; uint256 public lockedAmount; uint256 public exerciserFee = 50;//in tenth percent uint256 public expirerFee = 50;//in tenth percent uint256 public devFundBetFee = 2;//tenth of percent uint256 public poolLockSeconds = 7 days; uint256 public contractCreated; bool public open = true; Option[] public options; uint256 public tI = 0;//total interchange //reward amounts uint256 public fGS =400000000000000;//first gov stake reward uint256 public reward = 200000000000000; bool public rewEn = true;//rewards enabled modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } /* Types */ enum OptionType {Put, Call} struct Option { address payable holder; int256 sPrice;//strike uint256 pValue;//purchase uint256 lValue;//purchaseAmount+possible reward for correct bet uint256 exp;//expiration OptionType dir;//direction address pP;//price provider address altPA;//alt pool address } /* Events */ event Create( uint256 indexed id, address payable account, int256 sPrice,//strike uint256 lValue,//locked value OptionType dir, bool alt ); event Payout(uint256 poolLost, address winner); event Exercise(uint256 indexed id); event Expire(uint256 indexed id); constructor(string memory name_, string memory symbol_, address pp_, address biop_, address rateCalc_) public ERC20(name_, symbol_){ devFund = msg.sender; owner = msg.sender; biop = biop_; defaultRCAddress = rateCalc_; lockedAmount = 0; contractCreated = block.timestamp; ePairs[pp_] = defaultRCAddress; //default pair ETH/USD defaultPair = pp_; minT = 900;//15 minutes maxT = 60 minutes; } function getMaxAvailable() public view returns(uint256) { uint256 balance = address(this).balance; if (balance > lockedAmount) { return balance.sub(lockedAmount); } else { return 0; } } function getAltMaxAvailable(address erc20PoolAddress_) public view returns(uint256) { ERC20 alt = ERC20(erc20PoolAddress_); uint256 balance = alt.balanceOf(address(this)); if (balance > altLockedAmount[erc20PoolAddress_]) { return balance.sub( altLockedAmount[erc20PoolAddress_]); } else { return 0; } } function getOptionCount() public view returns(uint256) { return options.length; } function getStakingTimeBonus(address account) public view returns(uint256) { uint256 dif = block.timestamp.sub(lST[account]); uint256 bonus = dif.div(777600);//9 days if (dif < 777600) { return 1; } return bonus; } function getPoolBalanceBonus(address account) public view returns(uint256) { uint256 balance = balanceOf(account); if (balance > 0) { if (totalSupply() < 100) { //guard return 1; } if (balance >= totalSupply().div(2)) {//50th percentile return 20; } if (balance >= totalSupply().div(4)) {//25th percentile return 14; } if (balance >= totalSupply().div(5)) {//20th percentile return 10; } if (balance >= totalSupply().div(10)) {//10th percentile return 8; } if (balance >= totalSupply().div(20)) {//5th percentile return 6; } if (balance >= totalSupply().div(50)) {//2nd percentile return 4; } if (balance >= totalSupply().div(100)) {//1st percentile return 3; } return 2; } return 1; } function getOptionValueBonus(address account) public view returns(uint256) { uint256 dif = tI.sub(iAL[account]); uint256 bonus = dif.div(1000000000000000000);//1ETH if(bonus > 0){ return bonus; } return 0; } //used for betting/exercise/expire calc function getBetSizeBonus(uint256 amount, uint256 base) public view returns(uint256) { uint256 betPercent = totalSupply().mul(100).div(amount); if(base.mul(betPercent).div(10) > 0){ return base.mul(betPercent).div(10); } return base.div(1000); } function getCombinedStakingBonus(address account) public view returns(uint256) { return reward .mul(getStakingTimeBonus(account)) .mul(getPoolBalanceBonus(account)) .mul(getOptionValueBonus(account)); } function getPendingClaims(address account) public view returns(uint256) { if (balanceOf(account) > 1) { //staker reward bonus //base*(weeks)*(poolBalanceBonus/10)*optionsBacked return pClaims[account].add( getCombinedStakingBonus(account) ); } else { //normal rewards return pClaims[account]; } } function updateLPmetrics() internal { lST[msg.sender] = block.timestamp; iAL[msg.sender] = tI; } /** * @dev distribute pending governance token claims to user */ function claimRewards() external { BIOPTokenV3 b = BIOPTokenV3(biop); uint256 claims = getPendingClaims(msg.sender); if (balanceOf(msg.sender) > 1) { updateLPmetrics(); } pClaims[msg.sender] = 0; b.updateEarlyClaim(claims); } /** * @dev the default price provider. This is a convenience method */ function defaultPriceProvider() public view returns (address) { return defaultPair; } /** * @dev add a pool * @param newPool_ the address EBOP20 pool to add */ function addAltPool(address newPool_) external onlyOwner { ePools[newPool_] = true; } /** * @dev enable or disable BIOP rewards * @param nx_ the new position for the rewEn switch */ function enableRewards(bool nx_) external onlyOwner { rewEn = nx_; } /** * @dev remove a pool * @param oldPool_ the address EBOP20 pool to remove */ function removeAltPool(address oldPool_) external onlyOwner { ePools[oldPool_] = false; } /** * @dev add or update a price provider to the ePairs list. * @param newPP_ the address of the AggregatorProxy price provider contract address to add. * @param rateCalc_ the address of the RateCalc to use with this trading pair. */ function addPP(address newPP_, address rateCalc_) external onlyOwner { ePairs[newPP_] = rateCalc_; } /** * @dev remove a price provider from the ePairs list * @param oldPP_ the address of the AggregatorProxy price provider contract address to remove. */ function removePP(address oldPP_) external onlyOwner { ePairs[oldPP_] = 0x0000000000000000000000000000000000000000; } /** * @dev update the max time for option bets * @param newMax_ the new maximum time (in seconds) an option may be created for (inclusive). */ function setMaxT(uint256 newMax_) external onlyOwner { maxT = newMax_; } /** * @dev update the max time for option bets * @param newMin_ the new minimum time (in seconds) an option may be created for (inclusive). */ function setMinT(uint256 newMin_) external onlyOwner { minT = newMin_; } /** * @dev address of this contract, convenience method */ function thisAddress() public view returns (address){ return address(this); } /** * @dev set the fee users can recieve for exercising other users options * @param exerciserFee_ the new fee (in tenth percent) for exercising a options itm */ function updateExerciserFee(uint256 exerciserFee_) external onlyOwner { require(exerciserFee_ > 1 && exerciserFee_ < 500, "invalid fee"); exerciserFee = exerciserFee_; } /** * @dev set the fee users can recieve for expiring other users options * @param expirerFee_ the new fee (in tenth percent) for expiring a options */ function updateExpirerFee(uint256 expirerFee_) external onlyOwner { require(expirerFee_ > 1 && expirerFee_ < 50, "invalid fee"); expirerFee = expirerFee_; } /** * @dev set the fee users pay to buy an option * @param devFundBetFee_ the new fee (in tenth percent) to buy an option */ function updateDevFundBetFee(uint256 devFundBetFee_) external onlyOwner { require(devFundBetFee_ >= 0 && devFundBetFee_ < 50, "invalid fee"); devFundBetFee = devFundBetFee_; } /** * @dev update the pool stake lock up time. * @param newLockSeconds_ the new lock time, in seconds */ function updatePoolLockSeconds(uint256 newLockSeconds_) external onlyOwner { require(newLockSeconds_ >= 0 && newLockSeconds_ < 14 days, "invalid fee"); poolLockSeconds = newLockSeconds_; } /** * @dev used to transfer ownership * @param newOwner_ the address of governance contract which takes over control */ function transferOwner(address payable newOwner_) external onlyOwner { owner = newOwner_; } /** * @dev used to transfer devfund * @param newDevFund the address of governance contract which takes over control */ function transferDevFund(address payable newDevFund) external onlyOwner { devFund = newDevFund; } /** * @dev used to send this pool into EOL mode when a newer one is open */ function closeStaking() external onlyOwner { open = false; } /** * @dev send ETH to the pool. Recieve pETH token representing your claim. * If rewards are available recieve BIOP governance tokens as well. */ function stake() external payable { require(open == true, "pool deposits has closed"); require(msg.value >= 100, "stake to small"); if (balanceOf(msg.sender) == 0) { lW[msg.sender] = block.timestamp; pClaims[msg.sender] = pClaims[msg.sender].add(fGS); } updateLPmetrics(); nW[msg.sender] = block.timestamp + poolLockSeconds;//this one is seperate because it isn't updated on reward claim _mint(msg.sender, msg.value); } /** * @dev recieve ETH from the pool. * If the current time is before your next available withdraw a 1% fee will be applied. * @param amount The amount of pETH to send the pool. */ function withdraw(uint256 amount) public { require (balanceOf(msg.sender) >= amount, "Insufficent Share Balance"); lW[msg.sender] = block.timestamp; uint256 valueToRecieve = amount.mul(address(this).balance).div(totalSupply()); _burn(msg.sender, amount); if (block.timestamp <= nW[msg.sender]) { //early withdraw fee uint256 penalty = valueToRecieve.div(100); require(devFund.send(penalty), "transfer failed"); require(msg.sender.send(valueToRecieve.sub(penalty)), "transfer failed"); } else { require(msg.sender.send(valueToRecieve), "transfer failed"); } } /** @dev helper for getting rate @param pair the price provider @param max max pool available @param deposit bet amount */ function getRate(address pair,uint256 max, uint256 deposit, int256 currentPrice) public view returns (uint256) { RateCalc rc = RateCalc(ePairs[pair]); return rc.rate(deposit, max.sub(deposit), uint256(pLP[pair]), uint256(currentPrice)); } /** @dev Open a new call or put options. @param type_ type of option to buy @param pp_ the address of the price provider to use (must be in the list of ePairs) @param time_ the time until your options expiration (must be minT < time_ > maxT) @param altPA_ address of alt pool. pass address of this contract to use ETH pool @param altA_ bet amount. only used if altPA_ != address(this) */ function bet(OptionType type_, address pp_, uint256 time_, address altPA_, uint256 altA_) external payable { require( type_ == OptionType.Call || type_ == OptionType.Put, "Wrong option type" ); require( time_ >= minT && time_ <= maxT, "Invalid time" ); require(ePairs[pp_] != 0x0000000000000000000000000000000000000000, "Invalid price provider"); AggregatorProxy priceProvider = AggregatorProxy(pp_); int256 latestPrice = priceProvider.latestAnswer(); uint256 depositValue; uint256 lockTotal; uint256 optionID = options.length; if (altPA_ != address(this)) { //do stuff specific to erc20 pool instead require(ePools[altPA_], "invalid pool"); IEBOP20 altPool = IEBOP20(altPA_); require(altPool.balanceOf(msg.sender) >= altA_, "invalid pool"); (depositValue, lockTotal) = altPool.bet(latestPrice, altA_); } else { //normal eth bet require(msg.value >= 100, "bet to small"); require(msg.value <= getMaxAvailable(), "bet to big"); //an optional (to be choosen by contract owner) fee on each option. //A % of the bet money is sent as a fee. see devFundBetFee if (devFundBetFee > 0) { uint256 fee = msg.value.div(devFundBetFee).div(100); require(devFund.send(fee), "devFund fee transfer failed"); depositValue = msg.value.sub(fee); } else { depositValue = msg.value; } uint256 lockValue = getRate(pp_, getMaxAvailable(), depositValue, latestPrice); if (rewEn) { pClaims[msg.sender] = pClaims[msg.sender].add(getBetSizeBonus(depositValue, reward)); } lockTotal = lockValue.add(depositValue); lock(lockTotal); } if (latestPrice != pLP[pp_]) { pLP[pp_] = latestPrice; } Option memory op = Option( msg.sender, latestPrice,//* depositValue, //* lockTotal,//* block.timestamp + time_,//time till expiration type_, pp_, altPA_ ); options.push(op); tI = tI.add(lockTotal); emit Create(optionID, msg.sender, latestPrice, lockTotal, type_, altPA_ == address(this)); } /** * @notice exercises a option * @param optionID id of the option to exercise */ function exercise(uint256 optionID) external { Option memory option = options[optionID]; require(block.timestamp <= option.exp, "expiration date margin has passed"); AggregatorProxy priceProvider = AggregatorProxy(option.pP); int256 latestPrice = priceProvider.latestAnswer(); //ETH bet if (option.dir == OptionType.Call) { require(latestPrice > option.sPrice, "price is to low"); } else { require(latestPrice < option.sPrice, "price is to high"); } if (option.altPA != address(this)) { IEBOP20 alt = IEBOP20(option.altPA); require(alt.payout(option.lValue,option.pValue, msg.sender, option.holder), "erc20 pool exercise failed"); } else { //option expires ITM, we pay out payout(option.lValue, msg.sender, option.holder); lockedAmount = lockedAmount.sub(option.lValue); } emit Exercise(optionID); if (rewEn) { pClaims[msg.sender] = pClaims[msg.sender].add(getBetSizeBonus(option.lValue, reward)); } } /** * @notice expires a option * @param optionID id of the option to expire */ function expire(uint256 optionID) external { Option memory option = options[optionID]; require(block.timestamp > option.exp, "expiration date has not passed"); if (option.altPA != address(this)) { //ERC20 option IEBOP20 alt = IEBOP20(option.altPA); require(alt.unlockAndPayExpirer(option.lValue,option.pValue, msg.sender), "erc20 pool exercise failed"); } else { //ETH option unlock(option.lValue, msg.sender); lockedAmount = lockedAmount.sub(option.lValue); } emit Expire(optionID); if (rewEn) { pClaims[msg.sender] = pClaims[msg.sender].add(getBetSizeBonus(option.pValue, reward)); } } /** @dev called by BinaryOptions contract to lock pool value coresponding to new binary options bought. @param amount amount in ETH to lock from the pool total. */ function lock(uint256 amount) internal { lockedAmount = lockedAmount.add(amount); } /** @dev called by BinaryOptions contract to unlock pool value coresponding to an option expiring otm. @param amount amount in ETH to unlock @param goodSamaritan the user paying to unlock these funds, they recieve a fee */ function unlock(uint256 amount, address payable goodSamaritan) internal { require(amount <= lockedAmount, "insufficent locked pool balance to unlock"); uint256 fee; if (amount <= 10000000000000000) {//small options give bigger fee % fee = amount.div(exerciserFee.mul(4)).div(100); } else { fee = amount.div(exerciserFee).div(100); } if (fee > 0) { require(goodSamaritan.send(fee), "good samaritan transfer failed"); } } /** @dev called by BinaryOptions contract to payout pool value coresponding to binary options expiring itm. @param amount amount in ETH to unlock @param exerciser address calling the exercise/expire function, this may the winner or another user who then earns a fee. @param winner address of the winner. @notice exerciser fees are subject to change see updateFeePercent above. */ function payout(uint256 amount, address payable exerciser, address payable winner) internal { require(amount <= lockedAmount, "insufficent pool balance available to payout"); require(amount <= address(this).balance, "insufficent balance in pool"); if (exerciser != winner) { //good samaratin fee uint256 fee; if (amount <= 10000000000000000) {//small options give bigger fee % fee = amount.div(exerciserFee.mul(4)).div(100); } else { fee = amount.div(exerciserFee).div(100); } if (fee > 0) { require(exerciser.send(fee), "exerciser transfer failed"); require(winner.send(amount.sub(fee)), "winner transfer failed"); } } else { require(winner.send(amount), "winner transfer failed"); } emit Payout(amount, winner); } }
* @dev given a continuous token supply, reserve token balance, reserve ratio, and a deposit amount (in the reserve token), calculates the return for a given conversion (in the continuous token) Formula: Return = _supply ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / MAX_RESERVE_RATIO) - 1) @param _supply continuous token total supply @param _reserveBalance total reserve token balance @param _reserveRatio reserve ratio, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in reserve token @return purchase return amount/ validate input special case for 0 deposit amount special case if the ratio = 100%
{ require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO, "Invalid inputs."); if (_depositAmount == 0) { return 0; } if (_reserveRatio == MAX_RESERVE_RATIO) { return _supply.mul(_depositAmount).div(_reserveBalance); } uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_reserveBalance); (result, precision) = power( baseN, _reserveBalance, _reserveRatio, MAX_RESERVE_RATIO ); uint256 newTokenSupply = _supply.mul(result) >> precision; return newTokenSupply.sub(_supply); }
2,186,449
[ 1, 10822, 279, 17235, 1147, 14467, 16, 20501, 1147, 11013, 16, 20501, 7169, 16, 471, 279, 443, 1724, 3844, 261, 267, 326, 20501, 1147, 3631, 17264, 326, 327, 364, 279, 864, 4105, 261, 267, 326, 17235, 1147, 13, 26758, 30, 2000, 273, 389, 2859, 1283, 225, 14015, 21, 397, 389, 323, 1724, 6275, 342, 389, 455, 6527, 13937, 13, 3602, 261, 67, 455, 6527, 8541, 342, 4552, 67, 862, 2123, 3412, 67, 54, 789, 4294, 13, 300, 404, 13, 225, 389, 2859, 1283, 2868, 17235, 1147, 2078, 14467, 225, 389, 455, 6527, 13937, 565, 2078, 20501, 1147, 11013, 225, 389, 455, 6527, 8541, 377, 20501, 7169, 16, 10584, 316, 293, 7755, 16, 404, 17, 21, 9449, 225, 389, 323, 1724, 6275, 4202, 443, 1724, 3844, 16, 316, 20501, 1147, 225, 327, 23701, 327, 3844, 19, 1954, 810, 4582, 648, 364, 374, 443, 1724, 3844, 4582, 648, 309, 326, 7169, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 288, 203, 3639, 2583, 24899, 2859, 1283, 405, 374, 597, 389, 455, 6527, 13937, 405, 374, 597, 389, 455, 6527, 8541, 405, 374, 597, 389, 455, 6527, 8541, 1648, 4552, 67, 862, 2123, 3412, 67, 54, 789, 4294, 16, 315, 1941, 4540, 1199, 1769, 203, 3639, 309, 261, 67, 323, 1724, 6275, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 309, 261, 67, 455, 6527, 8541, 422, 4552, 67, 862, 2123, 3412, 67, 54, 789, 4294, 13, 288, 203, 5411, 327, 389, 2859, 1283, 18, 16411, 24899, 323, 1724, 6275, 2934, 2892, 24899, 455, 6527, 13937, 1769, 203, 3639, 289, 203, 3639, 2254, 5034, 563, 31, 203, 3639, 2254, 28, 6039, 31, 203, 3639, 2254, 5034, 1026, 50, 273, 389, 323, 1724, 6275, 18, 1289, 24899, 455, 6527, 13937, 1769, 203, 3639, 261, 2088, 16, 6039, 13, 273, 7212, 12, 203, 5411, 1026, 50, 16, 389, 455, 6527, 13937, 16, 389, 455, 6527, 8541, 16, 4552, 67, 862, 2123, 3412, 67, 54, 789, 4294, 203, 3639, 11272, 203, 3639, 2254, 5034, 394, 1345, 3088, 1283, 273, 389, 2859, 1283, 18, 16411, 12, 2088, 13, 1671, 6039, 31, 203, 3639, 327, 394, 1345, 3088, 1283, 18, 1717, 24899, 2859, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.4; import "./libraries/multicall.sol"; import "./libraries/Math.sol"; import "./libraries/FixedPoints.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; // import "hardhat/console.sol"; contract veiZi is Ownable, Multicall, ReentrancyGuard, ERC721Enumerable, IERC721Receiver { using SafeERC20 for IERC20; /// @dev Point of epochs /// for each epoch, y = bias - (t - timestamp) * slope struct Point { int256 bias; int256 slope; // start of segment uint256 timestamp; } /// @dev locked info of a nft struct LockedBalance { // amount of token locked int256 amount; // end block uint256 end; } int128 constant DEPOSIT_FOR_TYPE = 0; int128 constant CREATE_LOCK_TYPE = 1; int128 constant INCREASE_LOCK_AMOUNT = 2; int128 constant INCREASE_UNLOCK_TIME = 3; /// @notice emit if successfully deposit (calling increaseAmount, createLock, increaseUnlockTime) /// @param nftId id of nft, starts from 1 /// @param value amount of token locked /// @param lockBlk end block /// @param depositType createLock / increaseAmount / increaseUnlockTime / depositFor /// @param timestamp start timestamp event Deposit(uint256 indexed nftId, uint256 value, uint256 indexed lockBlk, int128 depositType, uint256 timestamp); /// @notice emit if successfuly withdraw /// @param nftId id of nft, starts from 1 /// @param value amount of token released /// @param timestamp block timestamp when calling withdraw(...) event Withdraw(uint256 indexed nftId, uint256 value, uint256 timestamp); /// @notice emit if an user successfully staked a nft /// @param nftId id of nft, starts from 1 /// @param owner address of user event Stake(uint256 indexed nftId, address indexed owner); /// @notice emit if an user unstaked a staked nft /// @param nftId id of nft, starts from 1 /// @param owner address of user event Unstake(uint256 indexed nftId, address indexed owner); /// @notice emit if the total amount of locked token changes /// @param preSupply total amount before change /// @param supply total amount after change event Supply(uint256 preSupply, uint256 supply); /// @notice number of block in a week (estimated) uint256 public WEEK; /// @notice number of block for 4 years uint256 public MAXTIME; /// @notice block delta uint256 public secondsPerBlockX64; /// @notice erc-20 token to lock address public token; /// @notice total amount of locked token uint256 public supply; /// @notice num of nft generated uint256 public nftNum = 0; /// @notice locked info for each nft mapping(uint256 => LockedBalance) public nftLocked; uint256 public epoch; /// @notice weight-curve(veiZi amount) of total-weight for all nft mapping(uint256 => Point) public pointHistory; mapping(uint256 => int256) public slopeChanges; /// @notice weight-curve of each nft mapping(uint256 => mapping(uint256 => Point)) public nftPointHistory; mapping(uint256 => uint256) public nftPointEpoch; /// @notice total num of nft staked uint256 public stakeNum = 0; // +1 every time when calling stake(...) /// @notice total amount of staked iZi uint256 public stakeiZiAmount = 0; struct StakingStatus { uint256 stakingId; uint256 lockAmount; uint256 lastVeiZi; uint256 lastTouchBlock; uint256 lastTouchAccRewardPerShare; } /// @notice nftId to staking status mapping(uint256 => StakingStatus) public stakingStatus; /// @notice owner address of staked nft mapping(uint256 => address) public stakedNftOwners; /// @notice nftid the user staked, 0 for no staked. each user can stake at most 1 nft mapping(address => uint256) public stakedNft; string public baseTokenURI; mapping(uint256 => address) public delegateAddress; struct RewardInfo { /// @dev who provides reward address provider; /// @dev Accumulated Reward Tokens per share, times Q128. uint256 accRewardPerShare; /// @dev Reward amount for each block. uint256 rewardPerBlock; /// @dev Last block number that the accRewardRerShare is touched. uint256 lastTouchBlock; /// @dev The block number when NFT mining rewards starts/ends. uint256 startBlock; /// @dev The block number when NFT mining rewards starts/ends. uint256 endBlock; } /// @dev reward infos RewardInfo public rewardInfo; modifier checkAuth(uint256 nftId, bool allowStaked) { bool auth = _isApprovedOrOwner(msg.sender, nftId); if (allowStaked) { auth = auth || (stakedNft[msg.sender] == nftId); } require(auth, "Not Owner or Not exist!"); _; } /// @notice constructor /// @param tokenAddr address of locked token /// @param _rewardInfo reward info constructor(address tokenAddr, RewardInfo memory _rewardInfo) ERC721("iZUMi DAO veNFT", "veiZi") { token = tokenAddr; pointHistory[0].timestamp = block.timestamp; WEEK = 7 * 24 * 3600; MAXTIME = (4 * 365 + 1) * 24 * 3600; rewardInfo = _rewardInfo; rewardInfo.accRewardPerShare = 0; rewardInfo.lastTouchBlock = Math.max(_rewardInfo.startBlock, block.number); } /// @notice Used for ERC721 safeTransferFrom function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } /// @notice get slope of last epoch of weight-curve of an nft /// @param nftId id of nft, starts from 1 function getLastNftSlope(uint256 nftId) external view returns(int256) { uint256 uepoch = nftPointEpoch[nftId]; return nftPointHistory[nftId][uepoch].slope; } struct CheckPointState { int256 oldDslope; int256 newDslope; uint256 _epoch; } function _checkPoint(uint256 nftId, LockedBalance memory oldLocked, LockedBalance memory newLocked) internal { Point memory uOld; Point memory uNew; CheckPointState memory cpState; cpState.oldDslope = 0; cpState.newDslope = 0; cpState._epoch = epoch; if (nftId != 0) { if (oldLocked.end > block.timestamp && oldLocked.amount > 0) { uOld.slope = oldLocked.amount / int256(MAXTIME); uOld.bias = uOld.slope * int256(oldLocked.end - block.timestamp); } if (newLocked.end > block.timestamp && newLocked.amount > 0) { uNew.slope = newLocked.amount / int256(MAXTIME); uNew.bias = uNew.slope * int256(newLocked.end - block.timestamp); } cpState.oldDslope = slopeChanges[oldLocked.end]; if (newLocked.end != 0) { if (newLocked.end == oldLocked.end) { cpState.newDslope = cpState.oldDslope; } else { cpState.newDslope = slopeChanges[newLocked.end]; } } } Point memory lastPoint = Point({bias: 0, slope: 0, timestamp: block.timestamp}); if (cpState._epoch > 0) { lastPoint = pointHistory[cpState._epoch]; } uint256 lastCheckPoint = lastPoint.timestamp; uint256 ti = (lastCheckPoint / WEEK) * WEEK; for (uint24 i = 0; i < 255; i ++) { ti += WEEK; int256 dSlope = 0; if (ti > block.timestamp) { ti = block.timestamp; } else { dSlope = slopeChanges[ti]; } // ti >= lastCheckPoint lastPoint.bias -= lastPoint.slope * int256(ti - lastCheckPoint); lastPoint.slope += dSlope; if (lastPoint.bias < 0) { lastPoint.bias = 0; } if (lastPoint.slope < 0) { lastPoint.slope = 0; } lastCheckPoint = ti; lastPoint.timestamp = ti; if (ti == block.timestamp) { cpState._epoch += 1; break; } else { if (dSlope != 0) { // slope changes cpState._epoch += 1; pointHistory[cpState._epoch] = lastPoint; } } } epoch = cpState._epoch; if (nftId != 0) { lastPoint.slope += (uNew.slope - uOld.slope); lastPoint.bias += (uNew.bias - uOld.bias); if (lastPoint.slope < 0) { lastPoint.slope = 0; } if (lastPoint.bias < 0) { lastPoint.bias = 0; } } pointHistory[cpState._epoch] = lastPoint; if (nftId != 0) { if (oldLocked.end > block.timestamp) { cpState.oldDslope += uOld.slope; if (newLocked.end == oldLocked.end) { cpState.oldDslope -= uNew.slope; } slopeChanges[oldLocked.end] = cpState.oldDslope; } if (newLocked.end > block.timestamp) { if (newLocked.end > oldLocked.end) { cpState.newDslope -= uNew.slope; slopeChanges[newLocked.end] = cpState.newDslope; } } uint256 nftEpoch = nftPointEpoch[nftId] + 1; uNew.timestamp = block.timestamp; nftPointHistory[nftId][nftEpoch] = uNew; nftPointEpoch[nftId] = nftEpoch; } } function _depositFor(uint256 nftId, uint256 _value, uint256 unlockTime, LockedBalance memory lockedBalance, int128 depositType) internal { LockedBalance memory _locked = lockedBalance; uint256 supplyBefore = supply; supply = supplyBefore + _value; LockedBalance memory oldLocked = LockedBalance({amount: _locked.amount, end: _locked.end}); _locked.amount += int256(_value); if (unlockTime != 0) { _locked.end = unlockTime; } _checkPoint(nftId, oldLocked, _locked); nftLocked[nftId] = _locked; if (_value != 0) { IERC20(token).safeTransferFrom(msg.sender, address(this), _value); } emit Deposit(nftId, _value, _locked.end, depositType, block.timestamp); emit Supply(supplyBefore, supplyBefore + _value); } /// @notice update global curve status to current block function checkPoint() external { _checkPoint(0, LockedBalance({amount: 0, end: 0}), LockedBalance({amount: 0, end: 0})); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { baseTokenURI = baseURI; } /// @notice create a new lock and generate a new nft /// @param _value amount of token to lock /// @param _unlockTime future timestamp to unlock /// @return nftId id of generated nft, starts from 1 function createLock(uint256 _value, uint256 _unlockTime) external nonReentrant returns(uint256 nftId) { uint256 unlockTime = (_unlockTime / WEEK) * WEEK; nftNum ++; nftId = nftNum; // id starts from 1 _mint(msg.sender, nftId); LockedBalance memory _locked = nftLocked[nftId]; require(_value > 0, "Amount should >0"); require(_locked.amount == 0, "Withdraw old tokens first"); require(unlockTime > block.timestamp, "Can only lock until time in the future"); require(unlockTime <= block.timestamp + MAXTIME, "Voting lock can be 4 years max"); _depositFor(nftId, _value, unlockTime, _locked, CREATE_LOCK_TYPE); } /// @notice increase amount of locked token in an nft /// @param nftId id of nft, starts from 1 /// @param _value increase amount function increaseAmount(uint256 nftId, uint256 _value) external nonReentrant { LockedBalance memory _locked = nftLocked[nftId]; require(_value > 0, "Amount should >0"); require(_locked.end > block.timestamp, "Can only lock until time in the future"); _depositFor(nftId, _value, 0, _locked, (msg.sender == ownerOf(nftId) || stakedNft[msg.sender] == nftId) ? INCREASE_LOCK_AMOUNT : DEPOSIT_FOR_TYPE); if (stakingStatus[nftId].stakingId != 0) { _updateGlobalStatus(); // this nft is staking // donot collect reward stakeiZiAmount += _value; stakingStatus[nftId].lockAmount += _value; } } /// @notice increase unlock time of an nft /// @param nftId id of nft /// @param _unlockTime future block number to unlock function increaseUnlockTime(uint256 nftId, uint256 _unlockTime) external checkAuth(nftId, true) nonReentrant { LockedBalance memory _locked = nftLocked[nftId]; uint256 unlockTime = (_unlockTime / WEEK) * WEEK; require(unlockTime > _locked.end, "Can only increase unlock time"); require(unlockTime > block.timestamp, "Can only lock until time in the future"); require(unlockTime <= block.timestamp + MAXTIME, "Voting lock can be 4 years max"); _depositFor(nftId, 0, unlockTime, _locked, INCREASE_UNLOCK_TIME); if (stakingStatus[nftId].stakingId != 0) { // this nft is staking address stakingOwner = stakedNftOwners[nftId]; _collectReward(nftId, stakingOwner); } } /// @notice withdraw an unstaked-nft /// @param nftId id of nft function withdraw(uint256 nftId) external checkAuth(nftId, false) nonReentrant { LockedBalance memory _locked = nftLocked[nftId]; require(block.timestamp >= _locked.end, "The lock didn't expire"); uint256 value = uint256(_locked.amount); LockedBalance memory oldLocked = LockedBalance({amount: _locked.amount, end: _locked.end}); _locked.end = 0; _locked.amount = 0; nftLocked[nftId] = _locked; uint256 supplyBefore = supply; supply = supplyBefore - value; _checkPoint(nftId, oldLocked, _locked); IERC20(token).safeTransfer(msg.sender, value); emit Withdraw(nftId, value, block.timestamp); emit Supply(supplyBefore, supplyBefore - value); } /// @notice burn an unstaked-nft (dangerous!!!) /// @param nftId id of nft function burn(uint256 nftId) external checkAuth(nftId, false) nonReentrant { LockedBalance memory _locked = nftLocked[nftId]; require(_locked.amount == 0, "Not Withdrawed!"); _burn(nftId); } /// @notice merge nftFrom to nftTo /// @param nftFrom nft id of nftFrom, cannot be staked, owner must be msg.sender /// @param nftTo nft id of nftTo, cannot be staked, owner must be msg.sender function merge(uint256 nftFrom, uint256 nftTo) external nonReentrant { require(_isApprovedOrOwner(msg.sender, nftFrom), "Not Owner of nftFrom"); require(_isApprovedOrOwner(msg.sender, nftTo), "Not Owner of nftTo"); require(stakingStatus[nftFrom].stakingId == 0, "nftFrom is staked"); require(stakingStatus[nftTo].stakingId == 0, "nftTo is staked"); require(nftFrom != nftTo, 'Same nft!'); LockedBalance memory lockedFrom = nftLocked[nftFrom]; LockedBalance memory lockedTo = nftLocked[nftTo]; require(lockedTo.end >= lockedFrom.end, "Endblock: nftFrom > nftTo"); // cancel lockedFrom in the weight-curve _checkPoint(nftFrom, LockedBalance({amount: lockedFrom.amount, end: lockedFrom.end}), LockedBalance({amount: 0, end: lockedFrom.end})); // add locked iZi of nftFrom to nftTo _checkPoint(nftTo, LockedBalance({amount: lockedTo.amount, end: lockedTo.end}), LockedBalance({amount: lockedTo.amount + lockedFrom.amount, end: lockedTo.end})); nftLocked[nftFrom].amount = 0; nftLocked[nftTo].amount = lockedTo.amount + lockedFrom.amount; } function _findTimestampEpoch(uint256 _timestamp, uint256 maxEpoch) internal view returns(uint256) { uint256 _min = 0; uint256 _max = maxEpoch; for (uint24 i = 0; i < 128; i ++) { if (_min >= _max) { break; } uint256 _mid = (_min + _max + 1) / 2; if (pointHistory[_mid].timestamp <= _timestamp) { _min = _mid; } else { _max = _mid - 1; } } return _min; } function _findNftTimestampEpoch(uint256 nftId, uint256 _timestamp) internal view returns(uint256) { uint256 _min = 0; uint256 _max = nftPointEpoch[nftId]; for (uint24 i = 0; i < 128; i ++) { if (_min >= _max) { break; } uint256 _mid = (_min + _max + 1) / 2; if (nftPointHistory[nftId][_mid].timestamp <= _timestamp) { _min = _mid; } else { _max = _mid - 1; } } return _min; } /// @notice weight of nft (veiZi amount) at certain time after latest update of that nft /// @param nftId id of nft /// @param timestamp specified timestamp after latest update of this nft (amount change or end change) /// @return weight function nftVeiZi(uint256 nftId, uint256 timestamp) public view returns(uint256) { uint256 _epoch = nftPointEpoch[nftId]; if (_epoch == 0) { return 0; } else { Point memory lastPoint = nftPointHistory[nftId][_epoch]; require(timestamp >= lastPoint.timestamp, "Too early"); lastPoint.bias -= lastPoint.slope * int256(timestamp - lastPoint.timestamp); if (lastPoint.bias < 0) { lastPoint.bias = 0; } return uint256(lastPoint.bias); } } /// @notice weight of nft (veiZi amount) at certain time /// @param nftId id of nft /// @param timestamp specified timestamp after latest update of this nft (amount change or end change) /// @return weight function nftVeiZiAt(uint256 nftId, uint256 timestamp) public view returns(uint256) { uint256 targetEpoch = _findNftTimestampEpoch(nftId, timestamp); Point memory uPoint = nftPointHistory[nftId][targetEpoch]; if (timestamp < uPoint.timestamp) { return 0; } uPoint.bias -= uPoint.slope * (int256(timestamp) - int256(uPoint.timestamp)); if (uPoint.bias < 0) { uPoint.bias = 0; } return uint256(uPoint.bias); } function _totalVeiZiAt(Point memory point, uint256 timestamp) internal view returns(uint256) { Point memory lastPoint = point; uint256 ti = (lastPoint.timestamp / WEEK) * WEEK; for (uint24 i = 0; i < 255; i ++) { ti += WEEK; int256 dSlope = 0; if (ti > timestamp) { ti = timestamp; } else { dSlope = slopeChanges[ti]; } lastPoint.bias -= lastPoint.slope * int256(ti - lastPoint.timestamp); if (lastPoint.bias <= 0) { lastPoint.bias = 0; break; } if (ti == timestamp) { break; } lastPoint.slope += dSlope; lastPoint.timestamp = ti; } return uint256(lastPoint.bias); } /// @notice total weight of all nft at a certain time after check-point of all-nft-collection's curve /// @param timestamp specified blockNumber, "certain time" in above line /// @return total weight function totalVeiZi(uint256 timestamp) external view returns(uint256) { uint256 _epoch = epoch; Point memory lastPoint = pointHistory[_epoch]; require(timestamp >= lastPoint.timestamp, "Too Early"); return _totalVeiZiAt(lastPoint, timestamp); } /// @notice total weight of all nft at a certain time /// @param timestamp specified blockNumber, "certain time" in above line /// @return total weight function totalVeiZiAt(uint256 timestamp) external view returns(uint256) { uint256 _epoch = epoch; uint256 targetEpoch = _findTimestampEpoch(timestamp, _epoch); Point memory point = pointHistory[targetEpoch]; if (timestamp < point.timestamp) { return 0; } if (targetEpoch == _epoch) { return _totalVeiZiAt(point, timestamp); } else { point.bias = point.bias - point.slope * (int256(timestamp) - int256(point.timestamp)); if (point.bias < 0) { point.bias = 0; } return uint256(point.bias); } } function _updateStakingStatus(uint256 nftId) internal { StakingStatus storage t = stakingStatus[nftId]; t.lastTouchBlock = rewardInfo.lastTouchBlock; t.lastTouchAccRewardPerShare = rewardInfo.accRewardPerShare; t.lastVeiZi = t.lockAmount / MAXTIME * (Math.max(block.timestamp, nftLocked[nftId].end) - block.timestamp); } /// @notice Collect pending reward for a single veizi-nft. /// @param nftId The related position id. /// @param recipient who acquires reward function _collectReward(uint256 nftId, address recipient) internal { StakingStatus memory t = stakingStatus[nftId]; _updateGlobalStatus(); uint256 reward = (t.lastVeiZi * (rewardInfo.accRewardPerShare - t.lastTouchAccRewardPerShare)) / FixedPoints.Q128; if (reward > 0) { IERC20(token).safeTransferFrom( rewardInfo.provider, recipient, reward ); } _updateStakingStatus(nftId); } function setDelegateAddress(uint256 nftId, address addr) external checkAuth(nftId, true) nonReentrant { delegateAddress[nftId] = addr; } function _beforeTokenTransfer(address from, address to, uint256 nftId) internal virtual override { super._beforeTokenTransfer(from, to, nftId); // when calling stake() or unStake() (to is contract address, or from is contract address) // delegateAddress will not change if (from != address(this) && to != address(this)) { delegateAddress[nftId] = address(0); } } /// @notice stake an nft /// @param nftId id of nft function stake(uint256 nftId) external nonReentrant { require(nftLocked[nftId].end > block.timestamp, "Lock expired"); // nftId starts from 1, zero or not owner(including staked) cannot be transfered safeTransferFrom(msg.sender, address(this), nftId); require(stakedNft[msg.sender] == 0, "Has Staked!"); _updateGlobalStatus(); stakedNft[msg.sender] = nftId; stakedNftOwners[nftId] = msg.sender; stakeNum += 1; uint256 lockAmount = uint256(nftLocked[nftId].amount); stakingStatus[nftId] = StakingStatus({ stakingId: stakeNum, lockAmount: lockAmount, lastVeiZi: lockAmount / MAXTIME * (Math.max(block.timestamp, nftLocked[nftId].end) - block.timestamp), lastTouchBlock: rewardInfo.lastTouchBlock, lastTouchAccRewardPerShare: rewardInfo.accRewardPerShare }); stakeiZiAmount += lockAmount; emit Stake(nftId, msg.sender); } /// @notice unstake an nft function unStake() external nonReentrant { uint256 nftId = stakedNft[msg.sender]; require(nftId != 0, "No Staked Nft!"); stakingStatus[nftId].stakingId = 0; stakedNft[msg.sender] = 0; stakedNftOwners[nftId] = address(0); _collectReward(nftId, msg.sender); // refund nft // note we can not use safeTransferFrom here because the // opterator is msg.sender who is not approved _safeTransfer(address(this), msg.sender, nftId, ""); stakeiZiAmount -= uint256(nftLocked[nftId].amount); emit Unstake(nftId, msg.sender); } /// @notice get user's staking info /// @param user address of user /// @return nftId id of veizi-nft /// @return stakingId id of stake /// @return amount amount of locked iZi in nft function stakingInfo(address user) external view returns(uint256 nftId, uint256 stakingId, uint256 amount) { nftId = stakedNft[user]; if (nftId != 0) { stakingId = stakingStatus[nftId].stakingId; amount = uint256(nftLocked[nftId].amount); uint256 remainBlock = Math.max(nftLocked[nftId].end, block.timestamp) - block.timestamp; amount = amount / MAXTIME * remainBlock; } else { stakingId = 0; amount = 0; } } /// @notice Update the global status. function _updateGlobalStatus() internal { if (block.number <= rewardInfo.lastTouchBlock) { return; } if (rewardInfo.lastTouchBlock >= rewardInfo.endBlock) { return; } uint256 currBlockNumber = Math.min(block.number, rewardInfo.endBlock); if (stakeiZiAmount == 0) { rewardInfo.lastTouchBlock = currBlockNumber; return; } // tokenReward < 2^25 * 2^64 * 2^10, 15 years, 1000 r/block uint256 tokenReward = (currBlockNumber - rewardInfo.lastTouchBlock) * rewardInfo.rewardPerBlock; // tokenReward * Q128 < 2^(25 + 64 + 10 + 128) rewardInfo.accRewardPerShare = rewardInfo.accRewardPerShare + ((tokenReward * FixedPoints.Q128) / stakeiZiAmount); rewardInfo.lastTouchBlock = currBlockNumber; } /// @notice Return reward multiplier over the given _from to _to block. /// @param _from The start block. /// @param _to The end block. function _getRewardBlockNum(uint256 _from, uint256 _to) internal view returns (uint256) { if (_from > _to) { return 0; } if (_to <= rewardInfo.endBlock) { return _to - _from; } else if (_from >= rewardInfo.endBlock) { return 0; } else { return rewardInfo.endBlock - _from; } } /// @notice View function to see pending Reward for a staked NFT. /// @param nftId The staked NFT id. /// @return reward iZi reward amount function pendingRewardOfToken(uint256 nftId) public view returns (uint256 reward) { reward = 0; StakingStatus memory t = stakingStatus[nftId]; if (t.stakingId != 0) { // we are sure that stakeiZiAmount is not 0 uint256 tokenReward = _getRewardBlockNum( rewardInfo.lastTouchBlock, block.number ) * rewardInfo.rewardPerBlock; // we are sure that stakeiZiAmount >= t.lockAmount > 0 uint256 rewardPerShare = rewardInfo.accRewardPerShare + (tokenReward * FixedPoints.Q128) / stakeiZiAmount; // l * (currentAcc - lastAcc) reward = (t.lastVeiZi * (rewardPerShare - t.lastTouchAccRewardPerShare)) / FixedPoints.Q128; } } /// @notice View function to see pending Reward for a user. /// @param user The related user address. /// @return reward iZi reward amount function pendingRewardOfAddress(address user) public view returns (uint256 reward) { reward = 0; uint256 nftId = stakedNft[user]; if (nftId != 0) { reward = pendingRewardOfToken(nftId); } } /// @notice collect pending reward if some user has a staked veizi-nft function collect() external nonReentrant { uint256 nftId = stakedNft[msg.sender]; require(nftId != 0, 'No Staked veizi-nft!'); _collectReward(nftId, msg.sender); } /// @notice Set new reward end block. /// @param endBlock New end block. function modifyEndBlock(uint256 endBlock) external onlyOwner { require(endBlock > block.number, "OUT OF DATE"); _updateGlobalStatus(); // jump if origin endBlock < block.number rewardInfo.lastTouchBlock = block.number; rewardInfo.endBlock = endBlock; } /// @notice Set new reward per block. /// @param _rewardPerBlock new reward per block function modifyRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { _updateGlobalStatus(); rewardInfo.rewardPerBlock = _rewardPerBlock; } function modifyStartBlock(uint256 startBlock) external onlyOwner { require(rewardInfo.startBlock > block.number, 'has started!'); require(startBlock > block.number, 'Too Early!'); require(startBlock < rewardInfo.endBlock, 'Too Late!'); rewardInfo.startBlock = startBlock; rewardInfo.lastTouchBlock = startBlock; // before start, lastTouchBlock = max(block.number, startBlock) } /// @notice Set new reward provider. /// @param provider New provider function modifyProvider(address provider) external onlyOwner { rewardInfo.provider = provider; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall { function multicall(bytes[] calldata data) external payable returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @title Simple math library for Max and Min. library Math { function max(int24 a, int24 b) internal pure returns (int24) { return a >= b ? a : b; } function min(int24 a, int24 b) internal pure returns (int24) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function tickFloor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 c = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) { c = c - 1; } c = c * tickSpacing; return c; } function tickUpper(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 c = tick / tickSpacing; if (tick > 0 && tick % tickSpacing != 0) { c = c + 1; } c = c * tickSpacing; return c; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library FixedPoints { uint256 constant Q32 = (1 << 32); uint256 constant Q64 = (1 << 64); uint256 constant Q96 = (1 << 96); uint256 constant Q128 = (1 << 128); uint256 constant Q160 = (1 << 160); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) 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 // 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 (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 (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 (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) 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); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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/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 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); }
@dev Point of epochs for each epoch, y = bias - (t - timestamp) * slope start of segment
struct Point { int256 bias; int256 slope; uint256 timestamp; }
460,149
[ 1, 2148, 434, 25480, 364, 1517, 7632, 16, 677, 273, 12005, 300, 261, 88, 300, 2858, 13, 225, 17543, 787, 434, 3267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 4686, 288, 203, 3639, 509, 5034, 12005, 31, 203, 3639, 509, 5034, 17543, 31, 203, 3639, 2254, 5034, 2858, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x676540d8C6687A7dF40bbb24233bb0345b313490/sources/browser/FarmStaking.sol
* @notice Safe reward transfer function, just in case a rounding error causes pool to not have enough reward tokens @param _to the user address to transfer tokens to @param _amount the total amount of tokens to transfer/
function safeRewardTransfer(address _to, uint256 _amount) internal { uint256 rewardBal = farmInfo.rewardToken.balanceOf(farmInfo.rewardHolder); if (_amount > rewardBal) { farmInfo.rewardToken.transferFrom(farmInfo.rewardHolder, _to, rewardBal); farmInfo.rewardToken.transferFrom(farmInfo.rewardHolder, _to, _amount); } }
8,283,786
[ 1, 9890, 19890, 7412, 445, 16, 2537, 316, 648, 279, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 19890, 2430, 225, 389, 869, 326, 729, 1758, 358, 7412, 2430, 358, 225, 389, 8949, 326, 2078, 3844, 434, 2430, 358, 7412, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4183, 17631, 1060, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 565, 2254, 5034, 19890, 38, 287, 273, 284, 4610, 966, 18, 266, 2913, 1345, 18, 12296, 951, 12, 74, 4610, 966, 18, 266, 2913, 6064, 1769, 203, 565, 309, 261, 67, 8949, 405, 19890, 38, 287, 13, 288, 203, 1377, 284, 4610, 966, 18, 266, 2913, 1345, 18, 13866, 1265, 12, 74, 4610, 966, 18, 266, 2913, 6064, 16, 389, 869, 16, 19890, 38, 287, 1769, 203, 1377, 284, 4610, 966, 18, 266, 2913, 1345, 18, 13866, 1265, 12, 74, 4610, 966, 18, 266, 2913, 6064, 16, 389, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract BrickAccessControl { constructor() public { admin = msg.sender; nodeToId[admin] = 1; } address public admin; address[] public nodes; mapping (address => uint) nodeToId; modifier onlyAdmin() { require(msg.sender == admin, "Not authorized admin"); _; } modifier onlyNode() { require(nodeToId[msg.sender] != 0, "Not authorized node"); _; } function setAdmin(address _newAdmin) public onlyAdmin { require(_newAdmin != address(0)); admin = _newAdmin; } function getNodes() public view returns (address[]) { return nodes; } function addNode(address _newNode) public onlyAdmin { require(_newNode != address(0), "Cannot set to empty address"); nodeToId[_newNode] = nodes.push(_newNode); } function removeNode(address _node) public onlyAdmin { require(_node != address(0), "Cannot set to empty address"); uint index = nodeToId[_node] - 1; delete nodes[index]; delete nodeToId[_node]; } } contract BrickBase is BrickAccessControl { /************** Events ***************/ // S201. λŒ€μΆœ 계약 생성 event ContractCreated(bytes32 loanId); // S201. λŒ€μΆœμ€‘ event ContractStarted(bytes32 loanId); // S301. μƒν™˜ μ™„λ£Œ event RedeemCompleted(bytes32 loanId); // S302. μ²­μ‚° μ™„λ£Œ event LiquidationCompleted(bytes32 loanId); /************** Data Types ***************/ struct Contract { bytes32 loanId; // 계약 번호 uint16 productId; // μƒν’ˆ 번호 bytes8 coinName; // 담보 코인 μ’…λ₯˜ uint256 coinAmount; // 담보 코인양 uint32 coinUnitPrice; // 1 코인당 κΈˆμ•‘ string collateralAddress; // 담보 μž…κΈˆ μ•”ν˜Έν™”ν μ£Όμ†Œ uint32 loanAmount; // λŒ€μΆœμ›κΈˆ uint64 createAt; // 계약일 uint64 openAt; // 원화지급일(κ°œμ‹œμΌ) uint64 expireAt; // 만기일 bytes8 feeRate; // 이자율 bytes8 overdueRate; // μ—°μ²΄μ΄μžμœ¨ bytes8 liquidationRate; // μ²­μ‚° 쑰건(담보 μ²­μ‚°λΉ„μœ¨) uint32 prepaymentFee; // μ€‘λ„μƒν™˜μˆ˜μˆ˜λ£Œ bytes32 extra; // 기타 정보 } struct ClosedContract { bytes32 loanId; // 계약 번호 bytes8 status; // μ’…λ£Œ νƒ€μž…(S301, S302) uint256 returnAmount; // λ°˜ν™˜μ½”μΈλŸ‰(μœ μ €μ—κ²Œ λŒλ €μ€€ 코인) uint32 returnCash; // λ°˜ν™˜ ν˜„κΈˆ(μœ μ €μ—κ²Œ λŒλ €μ€€ 원화) string returnAddress; // 담보 λ°˜ν™˜ μ•”ν˜Έν™”ν μ£Όμ†Œ uint32 feeAmount; // 총이자(이자 + μ—°μ²΄μ΄μž + 운영수수료 + μ‘°κΈ°μƒν™˜μˆ˜μˆ˜λ£Œ) uint32 evalUnitPrice; // μ²­μ‚°μ‹œμ  ν‰κ°€κΈˆμ•‘(1 코인당 κΈˆμ•‘) uint64 evalAt; // μ²­μ‚°μ‹œμ  평가일 uint64 closeAt; // μ’…λ£ŒμΌμž bytes32 extra; // 기타 정보 } /************** Storage ***************/ // 계약 번호 => λŒ€μΆœ κ³„μ•½μ„œ mapping (bytes32 => Contract) loanIdToContract; // 계약 번호 => μ’…λ£Œλœ λŒ€μΆœ κ³„μ•½μ„œ mapping (bytes32 => ClosedContract) loanIdToClosedContract; bytes32[] contracts; bytes32[] closedContracts; } contract BrickInterface is BrickBase { function createContract( bytes32 _loanId, uint16 _productId, bytes8 _coinName, uint256 _coinAmount, uint32 _coinUnitPrice, string _collateralAddress, uint32 _loanAmount, uint64[] _times, bytes8[] _rates, uint32 _prepaymentFee, bytes32 _extra) public; function closeContract( bytes32 _loanId, bytes8 _status, uint256 _returnAmount, uint32 _returnCash, string _returnAddress, uint32 _feeAmount, uint32 _evalUnitPrice, uint64 _evalAt, uint64 _closeAt, bytes32 _extra) public; function getContract(bytes32 _loanId) public view returns ( bytes32 loanId, uint16 productId, bytes8 coinName, uint256 coinAmount, uint32 coinUnitPrice, string collateralAddress, uint32 loanAmount, uint32 prepaymentFee, bytes32 extra); function getContractTimestamps(bytes32 _loanId) public view returns ( bytes32 loanId, uint64 createAt, uint64 openAt, uint64 expireAt); function getContractRates(bytes32 _loanId) public view returns ( bytes32 loanId, bytes8 feeRate, bytes8 overdueRate, bytes8 liquidationRate); function getClosedContract(bytes32 _loanId) public view returns ( bytes32 loanId, bytes8 status, uint256 returnAmount, uint32 returnCash, string returnAddress, uint32 feeAmount, uint32 evalUnitPrice, uint64 evalAt, uint64 closeAt, bytes32 extra); function totalContracts() public view returns (uint); function totalClosedContracts() public view returns (uint); } contract Brick is BrickInterface { /// @dev λŒ€μΆœ κ³„μ•½μ„œ μƒμ„±ν•˜κΈ° /// @param _loanId 계약 번호 /// @param _productId μƒν’ˆ 번호 /// @param _coinName 담보 코인 μ’…λ₯˜ /// @param _coinAmount 담보 코인양 /// @param _coinUnitPrice 1 코인당 κΈˆμ•‘ /// @param _collateralAddress 담보 μž…κΈˆ μ•”ν˜Έν™”ν μ£Όμ†Œ /// @param _loanAmount λŒ€μΆœμ›κΈˆ /// @param _times 계약 μ‹œκ°„ 정보[createAt, openAt, expireAt] /// @param _rates 이자율[feeRate, overdueRate, liquidationRate] /// @param _prepaymentFee μ€‘λ„μƒν™˜μˆ˜μˆ˜λ£Œ /// @param _extra 기타 정보 function createContract( bytes32 _loanId, uint16 _productId, bytes8 _coinName, uint256 _coinAmount, uint32 _coinUnitPrice, string _collateralAddress, uint32 _loanAmount, uint64[] _times, bytes8[] _rates, uint32 _prepaymentFee, bytes32 _extra) public onlyNode { require(loanIdToContract[_loanId].loanId == 0, "Already exists in Contract."); require(loanIdToClosedContract[_loanId].loanId == 0, "Already exists in ClosedContract."); Contract memory _contract = Contract({ loanId: _loanId, productId: _productId, coinName: _coinName, coinAmount: _coinAmount, coinUnitPrice: _coinUnitPrice, collateralAddress: _collateralAddress, loanAmount: _loanAmount, createAt: _times[0], openAt: _times[1], expireAt: _times[2], feeRate: _rates[0], overdueRate: _rates[1], liquidationRate: _rates[2], prepaymentFee: _prepaymentFee, extra: _extra }); loanIdToContract[_loanId] = _contract; contracts.push(_loanId); emit ContractCreated(_loanId); } /// @dev λŒ€μΆœ 계약 μ’…λ£Œν•˜κΈ° /// @param _loanId 계약 번호 /// @param _status μ’…λ£Œ νƒ€μž…(S301, S302) /// @param _returnAmount λ°˜ν™˜μ½”μΈλŸ‰(μœ μ €μ—κ²Œ λŒλ €μ€€ 코인) /// @param _returnCash λ°˜ν™˜ ν˜„κΈˆ(μœ μ €μ—κ²Œ λŒλ €μ€€ 원화) /// @param _returnAddress 담보 λ°˜ν™˜ μ•”ν˜Έν™”ν μ£Όμ†Œ /// @param _feeAmount 총이자(이자 + μ—°μ²΄μ΄μž + 운영수수료 + μ‘°κΈ°μƒν™˜μˆ˜μˆ˜λ£Œ) /// @param _evalUnitPrice μ²­μ‚°μ‹œμ  ν‰κ°€κΈˆμ•‘(1 코인당 κΈˆμ•‘) /// @param _evalAt μ²­μ‚°μ‹œμ  평가일 /// @param _closeAt μ’…λ£ŒμΌμž /// @param _extra 기타 정보 function closeContract( bytes32 _loanId, bytes8 _status, uint256 _returnAmount, uint32 _returnCash, string _returnAddress, uint32 _feeAmount, uint32 _evalUnitPrice, uint64 _evalAt, uint64 _closeAt, bytes32 _extra) public onlyNode { require(loanIdToContract[_loanId].loanId != 0, "Not exists in Contract."); require(loanIdToClosedContract[_loanId].loanId == 0, "Already exists in ClosedContract."); ClosedContract memory closedContract = ClosedContract({ loanId: _loanId, status: _status, returnAmount: _returnAmount, returnCash: _returnCash, returnAddress: _returnAddress, feeAmount: _feeAmount, evalUnitPrice: _evalUnitPrice, evalAt: _evalAt, closeAt: _closeAt, extra: _extra }); loanIdToClosedContract[_loanId] = closedContract; closedContracts.push(_loanId); if (_status == bytes16("S301")) { emit RedeemCompleted(_loanId); } else if (_status == bytes16("S302")) { emit LiquidationCompleted(_loanId); } } /// @dev 진행쀑인 λŒ€μΆœ κ³„μ•½μ„œ μ‘°νšŒν•˜κΈ° /// @param _loanId 계약 번호 /// @return The contract of given loanId function getContract(bytes32 _loanId) public view returns ( bytes32 loanId, uint16 productId, bytes8 coinName, uint256 coinAmount, uint32 coinUnitPrice, string collateralAddress, uint32 loanAmount, uint32 prepaymentFee, bytes32 extra) { require(loanIdToContract[_loanId].loanId != 0, "Not exists in Contract."); Contract storage c = loanIdToContract[_loanId]; loanId = c.loanId; productId = uint16(c.productId); coinName = c.coinName; coinAmount = uint256(c.coinAmount); coinUnitPrice = uint32(c.coinUnitPrice); collateralAddress = c.collateralAddress; loanAmount = uint32(c.loanAmount); prepaymentFee = uint32(c.prepaymentFee); extra = c.extra; } function getContractTimestamps(bytes32 _loanId) public view returns ( bytes32 loanId, uint64 createAt, uint64 openAt, uint64 expireAt) { require(loanIdToContract[_loanId].loanId != 0, "Not exists in Contract."); Contract storage c = loanIdToContract[_loanId]; loanId = c.loanId; createAt = uint64(c.createAt); openAt = uint64(c.openAt); expireAt = uint64(c.expireAt); } function getContractRates(bytes32 _loanId) public view returns ( bytes32 loanId, bytes8 feeRate, bytes8 overdueRate, bytes8 liquidationRate) { require(loanIdToContract[_loanId].loanId != 0, "Not exists in Contract."); Contract storage c = loanIdToContract[_loanId]; loanId = c.loanId; feeRate = c.feeRate; overdueRate = c.overdueRate; liquidationRate = c.liquidationRate; } /// @dev μ’…λ£Œλœ λŒ€μΆœ κ³„μ•½μ„œ μ‘°νšŒν•˜κΈ° /// @param _loanId 계약 번호 /// @return The closed contract of given loanId function getClosedContract(bytes32 _loanId) public view returns ( bytes32 loanId, bytes8 status, uint256 returnAmount, uint32 returnCash, string returnAddress, uint32 feeAmount, uint32 evalUnitPrice, uint64 evalAt, uint64 closeAt, bytes32 extra) { require(loanIdToClosedContract[_loanId].loanId != 0, "Not exists in ClosedContract."); ClosedContract storage c = loanIdToClosedContract[_loanId]; loanId = c.loanId; status = c.status; returnAmount = uint256(c.returnAmount); returnCash = uint32(c.returnCash); returnAddress = c.returnAddress; feeAmount = uint32(c.feeAmount); evalUnitPrice = uint32(c.evalUnitPrice); evalAt = uint64(c.evalAt); closeAt = uint64(c.closeAt); extra = c.extra; } function totalContracts() public view returns (uint) { return contracts.length; } function totalClosedContracts() public view returns (uint) { return closedContracts.length; } }
@dev λŒ€μΆœ 계약 μ’…λ£Œν•˜κΈ° @param _loanId 계약 번호 @param _status μ’…λ£Œ νƒ€μž…(S301, S302) @param _returnAmount λ°˜ν™˜μ½”μΈλŸ‰(μœ μ €μ—κ²Œ λŒλ €μ€€ 코인) @param _returnCash λ°˜ν™˜ ν˜„κΈˆ(μœ μ €μ—κ²Œ λŒλ €μ€€ 원화) @param _returnAddress 담보 λ°˜ν™˜ μ•”ν˜Έν™”ν μ£Όμ†Œ @param _feeAmount 총이자(이자 + μ—°μ²΄μ΄μž + 운영수수료 + μ‘°κΈ°μƒν™˜μˆ˜μˆ˜λ£Œ) @param _evalUnitPrice μ²­μ‚°μ‹œμ  ν‰κ°€κΈˆμ•‘(1 코인당 κΈˆμ•‘) @param _evalAt μ²­μ‚°μ‹œμ  평가일 @param _closeAt μ’…λ£ŒμΌμž @param _extra 기타 정보
function closeContract( bytes32 _loanId, bytes8 _status, uint256 _returnAmount, uint32 _returnCash, string _returnAddress, uint32 _feeAmount, uint32 _evalUnitPrice, uint64 _evalAt, uint64 _closeAt, bytes32 _extra) public onlyNode { require(loanIdToContract[_loanId].loanId != 0, "Not exists in Contract."); require(loanIdToClosedContract[_loanId].loanId == 0, "Already exists in ClosedContract."); ClosedContract memory closedContract = ClosedContract({ loanId: _loanId, status: _status, returnAmount: _returnAmount, returnCash: _returnCash, returnAddress: _returnAddress, feeAmount: _feeAmount, evalUnitPrice: _evalUnitPrice, evalAt: _evalAt, closeAt: _closeAt, extra: _extra }); loanIdToClosedContract[_loanId] = closedContract; closedContracts.push(_loanId); if (_status == bytes16("S301")) { emit RedeemCompleted(_loanId); emit LiquidationCompleted(_loanId); } }
888,586
[ 1, 172, 239, 227, 173, 119, 255, 225, 171, 116, 231, 173, 248, 126, 225, 173, 100, 232, 172, 101, 239, 174, 248, 251, 171, 121, 113, 225, 389, 383, 304, 548, 225, 171, 116, 231, 173, 248, 126, 225, 172, 115, 235, 174, 251, 121, 225, 389, 2327, 225, 173, 100, 232, 172, 101, 239, 225, 174, 230, 227, 173, 257, 232, 12, 55, 31831, 16, 348, 23, 3103, 13, 225, 389, 2463, 6275, 225, 172, 113, 251, 174, 252, 251, 173, 126, 247, 173, 256, 121, 172, 258, 236, 12, 173, 255, 259, 173, 259, 227, 173, 250, 243, 171, 115, 239, 225, 172, 242, 239, 172, 259, 102, 173, 102, 227, 225, 173, 126, 247, 173, 256, 121, 13, 225, 389, 2463, 39, 961, 225, 172, 113, 251, 174, 252, 251, 225, 174, 251, 231, 171, 121, 235, 12, 173, 255, 259, 173, 259, 227, 173, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 1746, 8924, 12, 203, 3639, 1731, 1578, 389, 383, 304, 548, 16, 1731, 28, 389, 2327, 16, 2254, 5034, 389, 2463, 6275, 16, 2254, 1578, 389, 2463, 39, 961, 16, 533, 389, 2463, 1887, 16, 203, 3639, 2254, 1578, 389, 21386, 6275, 16, 2254, 1578, 389, 8622, 2802, 5147, 16, 2254, 1105, 389, 8622, 861, 16, 2254, 1105, 389, 4412, 861, 16, 1731, 1578, 389, 7763, 13, 203, 3639, 1071, 203, 3639, 1338, 907, 203, 565, 288, 203, 3639, 2583, 12, 383, 304, 28803, 8924, 63, 67, 383, 304, 548, 8009, 383, 304, 548, 480, 374, 16, 315, 1248, 1704, 316, 13456, 1199, 1769, 203, 3639, 2583, 12, 383, 304, 28803, 7395, 8924, 63, 67, 383, 304, 548, 8009, 383, 304, 548, 422, 374, 16, 315, 9430, 1704, 316, 25582, 8924, 1199, 1769, 203, 203, 3639, 25582, 8924, 3778, 4375, 8924, 273, 25582, 8924, 12590, 203, 5411, 28183, 548, 30, 389, 383, 304, 548, 16, 203, 5411, 1267, 30, 389, 2327, 16, 203, 5411, 327, 6275, 30, 389, 2463, 6275, 16, 203, 5411, 327, 39, 961, 30, 389, 2463, 39, 961, 16, 203, 5411, 327, 1887, 30, 389, 2463, 1887, 16, 203, 5411, 14036, 6275, 30, 389, 21386, 6275, 16, 203, 5411, 5302, 2802, 5147, 30, 389, 8622, 2802, 5147, 16, 203, 5411, 5302, 861, 30, 389, 8622, 861, 16, 203, 5411, 1746, 861, 30, 389, 4412, 861, 16, 203, 5411, 2870, 30, 389, 7763, 203, 3639, 15549, 203, 3639, 28183, 28803, 7395, 8924, 63, 67, 383, 304, 548, 65, 273, 4375, 2 ]